Skip to main content

zlayer_overlay/
allocator.rs

1//! IP address allocation for overlay networks
2//!
3//! Manages allocation and tracking of overlay IP addresses within a CIDR range.
4//! Supports both IPv4 and IPv6 (dual-stack) networks.
5
6use crate::error::{OverlayError, Result};
7use ipnet::{IpNet, Ipv4Net, Ipv6Net};
8use serde::{Deserialize, Serialize};
9use std::collections::{HashMap, HashSet};
10use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
11use std::path::Path;
12
13/// IP allocator for overlay network addresses
14///
15/// Tracks allocated IP addresses and provides next-available allocation
16/// from a configured CIDR range. Supports both IPv4 and IPv6 networks.
17#[derive(Debug, Clone)]
18pub struct IpAllocator {
19    /// Network CIDR range (IPv4 or IPv6)
20    network: IpNet,
21    /// Set of allocated IP addresses
22    allocated: HashSet<IpAddr>,
23}
24
25/// Persistent state for IP allocator
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct IpAllocatorState {
28    /// CIDR string
29    pub cidr: String,
30    /// List of allocated IPs (serializes as strings, backward-compatible)
31    pub allocated: Vec<IpAddr>,
32}
33
34/// Increment an IPv6 address by a u128 offset from a base address.
35///
36/// Returns `None` if the result would overflow.
37fn ipv6_add(base: Ipv6Addr, offset: u128) -> Option<Ipv6Addr> {
38    let base_u128 = u128::from(base);
39    base_u128.checked_add(offset).map(Ipv6Addr::from)
40}
41
42/// Compute the number of host addresses for a given address family and prefix length.
43///
44/// For IPv4: `2^(32 - prefix) - 2` (excludes network and broadcast).
45/// For IPv6: `2^(128 - prefix) - 1` (excludes the network address).
46///
47/// Returns `None` if the result overflows u128 (only for /0 edge cases).
48fn host_count(is_ipv6: bool, prefix_len: u8) -> u128 {
49    if is_ipv6 {
50        let bits = 128 - u32::from(prefix_len);
51        if bits == 128 {
52            // /0 network — saturate
53            u128::MAX
54        } else if bits == 0 {
55            // /128 — single host, no usable addresses (it IS the network address)
56            0
57        } else {
58            // 2^bits - 1 (skip network address)
59            (1u128 << bits) - 1
60        }
61    } else {
62        let bits = 32 - u32::from(prefix_len);
63        if bits <= 1 {
64            // /31 or /32 — no usable hosts in classical networking
65            0
66        } else {
67            // 2^bits - 2 (skip network and broadcast)
68            (1u128 << bits) - 2
69        }
70    }
71}
72
73impl IpAllocator {
74    /// Create a new IP allocator for the given CIDR range
75    ///
76    /// Supports both IPv4 (e.g., "10.200.0.0/16") and IPv6 (e.g., `fd00::/48`).
77    ///
78    /// # Arguments
79    /// * `cidr` - Network CIDR notation
80    ///
81    /// # Errors
82    ///
83    /// Returns `OverlayError::InvalidCidr` if the CIDR string cannot be parsed.
84    ///
85    /// # Example
86    /// ```
87    /// use zlayer_overlay::allocator::IpAllocator;
88    ///
89    /// let v4 = IpAllocator::new("10.200.0.0/16").unwrap();
90    /// let v6 = IpAllocator::new("fd00::/48").unwrap();
91    /// ```
92    pub fn new(cidr: &str) -> Result<Self> {
93        let network: IpNet = cidr
94            .parse()
95            .map_err(|e| OverlayError::InvalidCidr(format!("{cidr}: {e}")))?;
96
97        Ok(Self {
98            network,
99            allocated: HashSet::new(),
100        })
101    }
102
103    /// Create an allocator from persisted state
104    ///
105    /// # Errors
106    ///
107    /// Returns an error if the CIDR is invalid or any IP is out of range.
108    pub fn from_state(state: IpAllocatorState) -> Result<Self> {
109        let mut allocator = Self::new(&state.cidr)?;
110        for ip in state.allocated {
111            allocator.mark_allocated(ip)?;
112        }
113        Ok(allocator)
114    }
115
116    /// Get the current state for persistence
117    #[must_use]
118    pub fn to_state(&self) -> IpAllocatorState {
119        IpAllocatorState {
120            cidr: self.network.to_string(),
121            allocated: self.allocated.iter().copied().collect(),
122        }
123    }
124
125    /// Load allocator state from a file
126    ///
127    /// # Errors
128    ///
129    /// Returns an error if the file cannot be read or the state is invalid.
130    pub async fn load(path: &Path) -> Result<Self> {
131        let contents = tokio::fs::read_to_string(path).await?;
132        let state: IpAllocatorState = serde_json::from_str(&contents)?;
133        Self::from_state(state)
134    }
135
136    /// Save allocator state to a file
137    ///
138    /// # Errors
139    ///
140    /// Returns an error if the file cannot be written or serialization fails.
141    pub async fn save(&self, path: &Path) -> Result<()> {
142        let state = self.to_state();
143        let contents = serde_json::to_string_pretty(&state)?;
144        tokio::fs::write(path, contents).await?;
145        Ok(())
146    }
147
148    /// Allocate the next available IP address
149    ///
150    /// For IPv4, skips the network and broadcast addresses.
151    /// For IPv6, skips the network address.
152    ///
153    /// Returns `None` if all addresses in the CIDR range are allocated.
154    ///
155    /// # Example
156    /// ```
157    /// use zlayer_overlay::allocator::IpAllocator;
158    ///
159    /// let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
160    /// let ip = allocator.allocate().unwrap();
161    /// assert_eq!(ip.to_string(), "10.200.0.1");
162    /// ```
163    pub fn allocate(&mut self) -> Option<IpAddr> {
164        match self.network {
165            IpNet::V4(v4net) => {
166                // IPv4: iterate hosts() which skips network and broadcast
167                for ip in v4net.hosts() {
168                    let addr = IpAddr::V4(ip);
169                    if !self.allocated.contains(&addr) {
170                        self.allocated.insert(addr);
171                        return Some(addr);
172                    }
173                }
174                None
175            }
176            IpNet::V6(v6net) => {
177                // IPv6: counter-based allocation starting from base+1
178                // We skip the network address itself (offset 0) and allocate from offset 1.
179                let base = v6net.network();
180                let total = host_count(true, v6net.prefix_len());
181
182                for offset in 1..=total {
183                    if let Some(candidate) = ipv6_add(base, offset) {
184                        let addr = IpAddr::V6(candidate);
185                        if !self.allocated.contains(&addr) {
186                            self.allocated.insert(addr);
187                            return Some(addr);
188                        }
189                    } else {
190                        break;
191                    }
192                }
193                None
194            }
195        }
196    }
197
198    /// Allocate a specific IP address
199    ///
200    /// # Errors
201    ///
202    /// Returns an error if the IP is already allocated or not in the CIDR range.
203    pub fn allocate_specific(&mut self, ip: IpAddr) -> Result<()> {
204        if !self.network.contains(&ip) {
205            return Err(OverlayError::IpNotInRange(ip, self.network.to_string()));
206        }
207
208        if self.allocated.contains(&ip) {
209            return Err(OverlayError::IpAlreadyAllocated(ip));
210        }
211
212        self.allocated.insert(ip);
213        Ok(())
214    }
215
216    /// Allocate the first usable IP in the range (typically for the leader)
217    ///
218    /// # Example
219    /// ```
220    /// use zlayer_overlay::allocator::IpAllocator;
221    ///
222    /// let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
223    /// let ip = allocator.allocate_first().unwrap();
224    /// assert_eq!(ip.to_string(), "10.200.0.1");
225    /// ```
226    ///
227    /// # Errors
228    ///
229    /// Returns an error if no IPs are available or the first IP is already allocated.
230    pub fn allocate_first(&mut self) -> Result<IpAddr> {
231        let first_ip = self.first_host().ok_or(OverlayError::NoAvailableIps)?;
232
233        if self.allocated.contains(&first_ip) {
234            return Err(OverlayError::IpAlreadyAllocated(first_ip));
235        }
236
237        self.allocated.insert(first_ip);
238        Ok(first_ip)
239    }
240
241    /// Get the first usable host address in the network.
242    ///
243    /// For IPv4: first host from `hosts()` (skips network address).
244    /// For IPv6: network address + 1 (skips the network address).
245    fn first_host(&self) -> Option<IpAddr> {
246        match self.network {
247            IpNet::V4(v4net) => v4net.hosts().next().map(IpAddr::V4),
248            IpNet::V6(v6net) => {
249                let base = v6net.network();
250                ipv6_add(base, 1).map(IpAddr::V6)
251            }
252        }
253    }
254
255    /// Mark an IP address as allocated (for restoring state)
256    ///
257    /// # Errors
258    ///
259    /// Returns an error if the IP is not in the CIDR range.
260    pub fn mark_allocated(&mut self, ip: IpAddr) -> Result<()> {
261        if !self.network.contains(&ip) {
262            return Err(OverlayError::IpNotInRange(ip, self.network.to_string()));
263        }
264        self.allocated.insert(ip);
265        Ok(())
266    }
267
268    /// Release an IP address back to the pool
269    ///
270    /// Returns `true` if the IP was released, `false` if it wasn't allocated.
271    pub fn release(&mut self, ip: IpAddr) -> bool {
272        self.allocated.remove(&ip)
273    }
274
275    /// Check if an IP address is allocated
276    #[must_use]
277    pub fn is_allocated(&self, ip: IpAddr) -> bool {
278        self.allocated.contains(&ip)
279    }
280
281    /// Check if an IP address is within the CIDR range
282    #[must_use]
283    pub fn contains(&self, ip: IpAddr) -> bool {
284        self.network.contains(&ip)
285    }
286
287    /// Get the number of allocated addresses
288    #[must_use]
289    pub fn allocated_count(&self) -> usize {
290        self.allocated.len()
291    }
292
293    /// Get the total number of usable addresses in the range
294    ///
295    /// For IPv6 networks with large host spaces, this saturates at `u32::MAX`.
296    #[must_use]
297    #[allow(clippy::cast_possible_truncation)]
298    pub fn total_hosts(&self) -> u32 {
299        let is_v6 = matches!(self.network, IpNet::V6(_));
300        let count = host_count(is_v6, self.network.prefix_len());
301        // Saturate to u32::MAX for enormous IPv6 subnets
302        if count > u128::from(u32::MAX) {
303            u32::MAX
304        } else {
305            count as u32
306        }
307    }
308
309    /// Get the number of available addresses
310    #[must_use]
311    #[allow(clippy::cast_possible_truncation)]
312    pub fn available_count(&self) -> u32 {
313        self.total_hosts()
314            .saturating_sub(self.allocated.len() as u32)
315    }
316
317    /// Get the CIDR string
318    #[must_use]
319    pub fn cidr(&self) -> String {
320        self.network.to_string()
321    }
322
323    /// Get the network address
324    #[must_use]
325    pub fn network_addr(&self) -> IpAddr {
326        self.network.network()
327    }
328
329    /// Get the broadcast address
330    ///
331    /// For IPv6, returns the last address in the range (all host bits set to 1).
332    #[must_use]
333    pub fn broadcast_addr(&self) -> IpAddr {
334        self.network.broadcast()
335    }
336
337    /// Get the prefix length
338    #[must_use]
339    pub fn prefix_len(&self) -> u8 {
340        self.network.prefix_len()
341    }
342
343    /// Get the host prefix length (32 for IPv4, 128 for IPv6)
344    #[must_use]
345    pub fn host_prefix_len(&self) -> u8 {
346        self.network.max_prefix_len()
347    }
348
349    /// Get all allocated IPs
350    #[must_use]
351    pub fn allocated_ips(&self) -> Vec<IpAddr> {
352        self.allocated.iter().copied().collect()
353    }
354}
355
356/// Leader-side allocator that carves per-node slices out of a cluster CIDR.
357///
358/// Used to fix the latent IP-collision bug where every agent independently
359/// allocated container IPs from the full cluster `/16`. With a `NodeSliceAllocator`
360/// the leader hands each joining node its own non-overlapping slice, and the
361/// agent-local `IpAllocator` is bounded to that slice.
362///
363/// Slice assignment is deterministic within a leader process: the node ID hashes
364/// to a candidate slice index; collisions are resolved by linear probing forward
365/// until a free slot is found. Existing assignments are preserved across leader
366/// restart via `snapshot()` / `restore()`.
367#[derive(Debug, Clone)]
368pub struct NodeSliceAllocator {
369    cluster_cidr: IpNet,
370    slice_prefix: u8,
371    assigned: HashMap<String, IpNet>,
372}
373
374/// Persistent snapshot of a `NodeSliceAllocator` for raft/disk persistence.
375#[derive(Debug, Clone, Serialize, Deserialize)]
376pub struct NodeSliceAllocatorSnapshot {
377    pub cluster_cidr: String,
378    pub slice_prefix: u8,
379    pub assigned: Vec<(String, String)>,
380}
381
382/// Deterministic FNV-1a 64-bit hash for a node ID string.
383///
384/// Chosen over `DefaultHasher` because `DefaultHasher` is seeded per-process
385/// and slice assignments should be reproducible from a snapshot.
386fn hash_node_id(node_id: &str) -> u64 {
387    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
388    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
389    let mut hash = FNV_OFFSET;
390    for &b in node_id.as_bytes() {
391        hash ^= u64::from(b);
392        hash = hash.wrapping_mul(FNV_PRIME);
393    }
394    hash
395}
396
397impl NodeSliceAllocator {
398    /// Create a new slice allocator that carves `/slice_prefix`-sized slices
399    /// out of `cluster_cidr`.
400    ///
401    /// # Errors
402    ///
403    /// Returns `OverlayError::InvalidCidr` if `slice_prefix` is not strictly
404    /// more specific than `cluster_cidr.prefix_len()`, or if it exceeds the
405    /// address family's maximum prefix length.
406    pub fn new(cluster_cidr: IpNet, slice_prefix: u8) -> Result<Self> {
407        if slice_prefix <= cluster_cidr.prefix_len() {
408            return Err(OverlayError::InvalidCidr(format!(
409                "slice prefix /{} must be more specific than cluster prefix /{}",
410                slice_prefix,
411                cluster_cidr.prefix_len()
412            )));
413        }
414        if slice_prefix > cluster_cidr.max_prefix_len() {
415            return Err(OverlayError::InvalidCidr(format!(
416                "slice prefix /{} exceeds address family max /{}",
417                slice_prefix,
418                cluster_cidr.max_prefix_len()
419            )));
420        }
421        Ok(Self {
422            cluster_cidr,
423            slice_prefix,
424            assigned: HashMap::new(),
425        })
426    }
427
428    /// Assign (or return an existing) slice for `node_id`.
429    ///
430    /// Idempotent: calling `assign` with a node ID that already has a slice
431    /// returns the existing slice without re-assigning.
432    ///
433    /// # Errors
434    ///
435    /// Returns `OverlayError::NoAvailableIps` if every slice in the cluster
436    /// CIDR is already assigned.
437    pub fn assign(&mut self, node_id: &str) -> Result<IpNet> {
438        if let Some(existing) = self.assigned.get(node_id) {
439            return Ok(*existing);
440        }
441
442        let num_slices = self.num_slices();
443        if num_slices == 0 {
444            return Err(OverlayError::NoAvailableIps);
445        }
446
447        let taken: HashSet<IpNet> = self.assigned.values().copied().collect();
448        let start = hash_node_id(node_id) % num_slices;
449
450        for i in 0..num_slices {
451            let idx = (start + i) % num_slices;
452            let slice = self.slice_at_index(idx);
453            if !taken.contains(&slice) {
454                self.assigned.insert(node_id.to_string(), slice);
455                return Ok(slice);
456            }
457        }
458
459        Err(OverlayError::NoAvailableIps)
460    }
461
462    /// Release `node_id`'s slice back to the free pool.
463    ///
464    /// Returns `true` if a slice was released, `false` if the node was not assigned.
465    pub fn release(&mut self, node_id: &str) -> bool {
466        self.assigned.remove(node_id).is_some()
467    }
468
469    /// Look up a node's assigned slice without mutating state.
470    #[must_use]
471    pub fn slice_for(&self, node_id: &str) -> Option<IpNet> {
472        self.assigned.get(node_id).copied()
473    }
474
475    /// Number of currently-assigned slices.
476    #[must_use]
477    pub fn assigned_count(&self) -> usize {
478        self.assigned.len()
479    }
480
481    /// Total number of slices the cluster CIDR can hold at the configured slice prefix.
482    #[must_use]
483    pub fn capacity(&self) -> u64 {
484        self.num_slices()
485    }
486
487    /// Cluster CIDR the allocator operates over.
488    #[must_use]
489    pub fn cluster_cidr(&self) -> IpNet {
490        self.cluster_cidr
491    }
492
493    /// Slice prefix length (e.g. `28` for `/28` slices).
494    #[must_use]
495    pub fn slice_prefix(&self) -> u8 {
496        self.slice_prefix
497    }
498
499    /// Build a persistable snapshot for durable leader state.
500    #[must_use]
501    pub fn snapshot(&self) -> NodeSliceAllocatorSnapshot {
502        NodeSliceAllocatorSnapshot {
503            cluster_cidr: self.cluster_cidr.to_string(),
504            slice_prefix: self.slice_prefix,
505            assigned: self
506                .assigned
507                .iter()
508                .map(|(k, v)| (k.clone(), v.to_string()))
509                .collect(),
510        }
511    }
512
513    /// Rebuild an allocator from a snapshot.
514    ///
515    /// # Errors
516    ///
517    /// Returns `OverlayError::InvalidCidr` if the snapshot's CIDR or any
518    /// assigned slice fails to parse, or if the slice prefix is inconsistent.
519    pub fn restore(snapshot: NodeSliceAllocatorSnapshot) -> Result<Self> {
520        let cluster_cidr: IpNet = snapshot
521            .cluster_cidr
522            .parse()
523            .map_err(|e| OverlayError::InvalidCidr(format!("{}: {e}", snapshot.cluster_cidr)))?;
524        let mut allocator = Self::new(cluster_cidr, snapshot.slice_prefix)?;
525        for (node_id, slice_str) in snapshot.assigned {
526            let slice: IpNet = slice_str
527                .parse()
528                .map_err(|e| OverlayError::InvalidCidr(format!("{slice_str}: {e}")))?;
529            if slice.prefix_len() != snapshot.slice_prefix {
530                return Err(OverlayError::InvalidCidr(format!(
531                    "assigned slice {slice} does not match configured prefix /{}",
532                    snapshot.slice_prefix
533                )));
534            }
535            if !cluster_cidr.contains(&slice.network()) {
536                return Err(OverlayError::InvalidCidr(format!(
537                    "assigned slice {slice} is not contained in cluster CIDR {cluster_cidr}"
538                )));
539            }
540            allocator.assigned.insert(node_id, slice);
541        }
542        Ok(allocator)
543    }
544
545    fn num_slices(&self) -> u64 {
546        let bits = self.slice_prefix - self.cluster_cidr.prefix_len();
547        // bits is in 1..=32 for v4 or 1..=128 for v6. For a /16 cluster with /28
548        // slices, bits = 12 → 4096 slices, safely inside u64 range.
549        if bits >= 64 {
550            u64::MAX
551        } else {
552            1u64 << bits
553        }
554    }
555
556    fn slice_at_index(&self, idx: u64) -> IpNet {
557        let shift = u32::from(self.cluster_cidr.max_prefix_len() - self.slice_prefix);
558        match self.cluster_cidr {
559            IpNet::V4(v4) => {
560                let base = u32::from(v4.network());
561                // idx fits in 32 bits whenever slice_prefix − cluster_prefix ≤ 32.
562                #[allow(clippy::cast_possible_truncation)]
563                let offset = (idx as u32).wrapping_shl(shift);
564                let slice_addr = Ipv4Addr::from(base.wrapping_add(offset));
565                IpNet::V4(
566                    Ipv4Net::new(slice_addr, self.slice_prefix)
567                        .expect("slice_prefix validated in constructor"),
568                )
569            }
570            IpNet::V6(v6) => {
571                let base = u128::from(v6.network());
572                let offset = u128::from(idx).wrapping_shl(shift);
573                let slice_addr = Ipv6Addr::from(base.wrapping_add(offset));
574                IpNet::V6(
575                    Ipv6Net::new(slice_addr, self.slice_prefix)
576                        .expect("slice_prefix validated in constructor"),
577                )
578            }
579        }
580    }
581}
582
583/// Helper function to get the first usable IP from a CIDR
584///
585/// Supports both IPv4 and IPv6 CIDR notation.
586///
587/// # Errors
588///
589/// Returns an error if the CIDR is invalid or has no usable hosts.
590pub fn first_ip_from_cidr(cidr: &str) -> Result<IpAddr> {
591    let network: IpNet = cidr
592        .parse()
593        .map_err(|e| OverlayError::InvalidCidr(format!("{cidr}: {e}")))?;
594
595    match network {
596        IpNet::V4(v4net) => v4net
597            .hosts()
598            .next()
599            .map(IpAddr::V4)
600            .ok_or(OverlayError::NoAvailableIps),
601        IpNet::V6(v6net) => {
602            let base = v6net.network();
603            ipv6_add(base, 1)
604                .map(IpAddr::V6)
605                .ok_or(OverlayError::NoAvailableIps)
606        }
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613    use std::net::{Ipv4Addr, Ipv6Addr};
614
615    /// Increment an IPv4 address by a u32 offset from a base address.
616    ///
617    /// Returns `None` if the result would overflow.
618    fn ipv4_add(base: Ipv4Addr, offset: u32) -> Option<Ipv4Addr> {
619        let base_u32 = u32::from(base);
620        base_u32.checked_add(offset).map(Ipv4Addr::from)
621    }
622
623    // ========================
624    // IPv4 Tests (existing, updated for IpAddr)
625    // ========================
626
627    #[test]
628    fn test_allocator_new() {
629        let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
630        assert_eq!(allocator.cidr(), "10.200.0.0/24");
631        assert_eq!(allocator.allocated_count(), 0);
632    }
633
634    #[test]
635    fn test_allocator_invalid_cidr() {
636        let result = IpAllocator::new("invalid");
637        assert!(result.is_err());
638    }
639
640    #[test]
641    fn test_allocate_sequential() {
642        let mut allocator = IpAllocator::new("10.200.0.0/30").unwrap();
643
644        // /30 has 2 usable hosts (excluding network and broadcast)
645        let ip1 = allocator.allocate().unwrap();
646        let ip2 = allocator.allocate().unwrap();
647
648        assert_eq!(ip1.to_string(), "10.200.0.1");
649        assert_eq!(ip2.to_string(), "10.200.0.2");
650
651        // Should be exhausted
652        assert!(allocator.allocate().is_none());
653    }
654
655    #[test]
656    fn test_allocate_first() {
657        let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
658
659        let first = allocator.allocate_first().unwrap();
660        assert_eq!(first.to_string(), "10.200.0.1");
661
662        // Can't allocate first again
663        assert!(allocator.allocate_first().is_err());
664    }
665
666    #[test]
667    fn test_allocate_specific() {
668        let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
669
670        let specific_ip: IpAddr = "10.200.0.50".parse().unwrap();
671        allocator.allocate_specific(specific_ip).unwrap();
672
673        assert!(allocator.is_allocated(specific_ip));
674
675        // Can't allocate same IP again
676        assert!(allocator.allocate_specific(specific_ip).is_err());
677    }
678
679    #[test]
680    fn test_allocate_specific_out_of_range() {
681        let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
682
683        let out_of_range: IpAddr = "192.168.1.1".parse().unwrap();
684        assert!(allocator.allocate_specific(out_of_range).is_err());
685    }
686
687    #[test]
688    fn test_release() {
689        let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
690
691        let ip = allocator.allocate().unwrap();
692        assert!(allocator.is_allocated(ip));
693
694        assert!(allocator.release(ip));
695        assert!(!allocator.is_allocated(ip));
696
697        // Can allocate same IP again
698        let ip2 = allocator.allocate().unwrap();
699        assert_eq!(ip, ip2);
700    }
701
702    #[test]
703    fn test_mark_allocated() {
704        let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
705
706        let ip: IpAddr = "10.200.0.100".parse().unwrap();
707        allocator.mark_allocated(ip).unwrap();
708
709        assert!(allocator.is_allocated(ip));
710    }
711
712    #[test]
713    fn test_contains() {
714        let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
715
716        assert!(allocator.contains("10.200.0.50".parse().unwrap()));
717        assert!(!allocator.contains("10.201.0.50".parse().unwrap()));
718    }
719
720    #[test]
721    fn test_total_hosts() {
722        // /24 has 254 usable hosts
723        let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
724        assert_eq!(allocator.total_hosts(), 254);
725
726        // /30 has 2 usable hosts
727        let allocator = IpAllocator::new("10.200.0.0/30").unwrap();
728        assert_eq!(allocator.total_hosts(), 2);
729    }
730
731    #[test]
732    fn test_available_count() {
733        let mut allocator = IpAllocator::new("10.200.0.0/30").unwrap();
734
735        assert_eq!(allocator.available_count(), 2);
736
737        allocator.allocate();
738        assert_eq!(allocator.available_count(), 1);
739
740        allocator.allocate();
741        assert_eq!(allocator.available_count(), 0);
742    }
743
744    #[test]
745    fn test_state_roundtrip() {
746        let mut allocator = IpAllocator::new("10.200.0.0/24").unwrap();
747        allocator.allocate();
748        allocator.allocate();
749
750        let state = allocator.to_state();
751        let restored = IpAllocator::from_state(state).unwrap();
752
753        assert_eq!(allocator.cidr(), restored.cidr());
754        assert_eq!(allocator.allocated_count(), restored.allocated_count());
755    }
756
757    #[test]
758    fn test_first_ip_from_cidr() {
759        let ip = first_ip_from_cidr("10.200.0.0/24").unwrap();
760        assert_eq!(ip.to_string(), "10.200.0.1");
761    }
762
763    #[test]
764    fn test_network_addr_v4() {
765        let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
766        assert_eq!(
767            allocator.network_addr(),
768            IpAddr::V4("10.200.0.0".parse().unwrap())
769        );
770    }
771
772    #[test]
773    fn test_broadcast_addr_v4() {
774        let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
775        assert_eq!(
776            allocator.broadcast_addr(),
777            IpAddr::V4("10.200.0.255".parse().unwrap())
778        );
779    }
780
781    #[test]
782    fn test_host_prefix_len_v4() {
783        let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
784        assert_eq!(allocator.host_prefix_len(), 32);
785    }
786
787    // ========================
788    // IPv6 Tests
789    // ========================
790
791    #[test]
792    fn test_allocator_new_v6() {
793        let allocator = IpAllocator::new("fd00::/48").unwrap();
794        assert_eq!(allocator.cidr(), "fd00::/48");
795        assert_eq!(allocator.allocated_count(), 0);
796    }
797
798    #[test]
799    fn test_allocate_sequential_v6() {
800        let mut allocator = IpAllocator::new("fd00::/126").unwrap();
801
802        // /126 has 3 usable hosts (4 addresses total, minus the network address)
803        let ip1 = allocator.allocate().unwrap();
804        let ip2 = allocator.allocate().unwrap();
805        let ip3 = allocator.allocate().unwrap();
806
807        assert_eq!(ip1.to_string(), "fd00::1");
808        assert_eq!(ip2.to_string(), "fd00::2");
809        assert_eq!(ip3.to_string(), "fd00::3");
810
811        // Should be exhausted
812        assert!(allocator.allocate().is_none());
813    }
814
815    #[test]
816    fn test_allocate_first_v6() {
817        let mut allocator = IpAllocator::new("fd00::/48").unwrap();
818
819        let first = allocator.allocate_first().unwrap();
820        assert_eq!(first.to_string(), "fd00::1");
821
822        // Can't allocate first again
823        assert!(allocator.allocate_first().is_err());
824    }
825
826    #[test]
827    fn test_allocate_specific_v6() {
828        let mut allocator = IpAllocator::new("fd00::/48").unwrap();
829
830        let specific_ip: IpAddr = "fd00::beef".parse().unwrap();
831        allocator.allocate_specific(specific_ip).unwrap();
832
833        assert!(allocator.is_allocated(specific_ip));
834
835        // Can't allocate same IP again
836        assert!(allocator.allocate_specific(specific_ip).is_err());
837    }
838
839    #[test]
840    fn test_allocate_specific_out_of_range_v6() {
841        let mut allocator = IpAllocator::new("fd00::/48").unwrap();
842
843        let out_of_range: IpAddr = "fe80::1".parse().unwrap();
844        assert!(allocator.allocate_specific(out_of_range).is_err());
845    }
846
847    #[test]
848    fn test_release_v6() {
849        let mut allocator = IpAllocator::new("fd00::/48").unwrap();
850
851        let ip = allocator.allocate().unwrap();
852        assert!(allocator.is_allocated(ip));
853
854        assert!(allocator.release(ip));
855        assert!(!allocator.is_allocated(ip));
856
857        // Can allocate same IP again
858        let ip2 = allocator.allocate().unwrap();
859        assert_eq!(ip, ip2);
860    }
861
862    #[test]
863    fn test_mark_allocated_v6() {
864        let mut allocator = IpAllocator::new("fd00::/48").unwrap();
865
866        let ip: IpAddr = "fd00::ff".parse().unwrap();
867        allocator.mark_allocated(ip).unwrap();
868
869        assert!(allocator.is_allocated(ip));
870    }
871
872    #[test]
873    fn test_contains_v6() {
874        let allocator = IpAllocator::new("fd00::/48").unwrap();
875
876        assert!(allocator.contains("fd00::50".parse().unwrap()));
877        assert!(!allocator.contains("fe80::1".parse().unwrap()));
878    }
879
880    #[test]
881    fn test_total_hosts_v6_small() {
882        // /126 has 3 usable hosts (skip network addr)
883        let allocator = IpAllocator::new("fd00::/126").unwrap();
884        assert_eq!(allocator.total_hosts(), 3);
885
886        // /127 has 1 usable host
887        let allocator = IpAllocator::new("fd00::/127").unwrap();
888        assert_eq!(allocator.total_hosts(), 1);
889    }
890
891    #[test]
892    fn test_total_hosts_v6_large() {
893        // /48 has 2^80 - 1 usable hosts, which saturates to u32::MAX
894        let allocator = IpAllocator::new("fd00::/48").unwrap();
895        assert_eq!(allocator.total_hosts(), u32::MAX);
896    }
897
898    #[test]
899    fn test_available_count_v6() {
900        let mut allocator = IpAllocator::new("fd00::/126").unwrap();
901
902        assert_eq!(allocator.available_count(), 3);
903
904        allocator.allocate();
905        assert_eq!(allocator.available_count(), 2);
906
907        allocator.allocate();
908        assert_eq!(allocator.available_count(), 1);
909
910        allocator.allocate();
911        assert_eq!(allocator.available_count(), 0);
912    }
913
914    #[test]
915    fn test_state_roundtrip_v6() {
916        let mut allocator = IpAllocator::new("fd00::/48").unwrap();
917        allocator.allocate();
918        allocator.allocate();
919
920        let state = allocator.to_state();
921
922        // Verify IpAddr serializes as strings (backward-compatible)
923        let json = serde_json::to_string_pretty(&state).unwrap();
924        assert!(json.contains("fd00::1"));
925        assert!(json.contains("fd00::2"));
926
927        let restored = IpAllocator::from_state(state).unwrap();
928
929        assert_eq!(allocator.cidr(), restored.cidr());
930        assert_eq!(allocator.allocated_count(), restored.allocated_count());
931    }
932
933    #[test]
934    fn test_first_ip_from_cidr_v6() {
935        let ip = first_ip_from_cidr("fd00::/48").unwrap();
936        assert_eq!(ip.to_string(), "fd00::1");
937    }
938
939    #[test]
940    fn test_network_addr_v6() {
941        let allocator = IpAllocator::new("fd00::/48").unwrap();
942        assert_eq!(
943            allocator.network_addr(),
944            IpAddr::V6("fd00::".parse().unwrap())
945        );
946    }
947
948    #[test]
949    fn test_broadcast_addr_v6() {
950        let allocator = IpAllocator::new("fd00::/126").unwrap();
951        assert_eq!(
952            allocator.broadcast_addr(),
953            IpAddr::V6("fd00::3".parse().unwrap())
954        );
955    }
956
957    #[test]
958    fn test_host_prefix_len_v6() {
959        let allocator = IpAllocator::new("fd00::/48").unwrap();
960        assert_eq!(allocator.host_prefix_len(), 128);
961    }
962
963    // ========================
964    // Cross-protocol tests
965    // ========================
966
967    #[test]
968    fn test_v4_and_v6_allocators_independent() {
969        let mut v4 = IpAllocator::new("10.200.0.0/30").unwrap();
970        let mut v6 = IpAllocator::new("fd00::/126").unwrap();
971
972        let v4_ip = v4.allocate().unwrap();
973        let v6_ip = v6.allocate().unwrap();
974
975        assert!(v4_ip.is_ipv4());
976        assert!(v6_ip.is_ipv6());
977        assert_eq!(v4_ip.to_string(), "10.200.0.1");
978        assert_eq!(v6_ip.to_string(), "fd00::1");
979    }
980
981    #[test]
982    fn test_ipv6_does_not_contain_ipv4() {
983        let allocator = IpAllocator::new("fd00::/48").unwrap();
984        assert!(!allocator.contains("10.200.0.1".parse().unwrap()));
985    }
986
987    #[test]
988    fn test_ipv4_does_not_contain_ipv6() {
989        let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
990        assert!(!allocator.contains("fd00::1".parse().unwrap()));
991    }
992
993    #[test]
994    fn test_allocate_specific_wrong_family() {
995        let mut v4_alloc = IpAllocator::new("10.200.0.0/24").unwrap();
996        let v6_ip: IpAddr = "fd00::1".parse().unwrap();
997        assert!(v4_alloc.allocate_specific(v6_ip).is_err());
998
999        let mut v6_alloc = IpAllocator::new("fd00::/48").unwrap();
1000        let v4_ip: IpAddr = "10.200.0.1".parse().unwrap();
1001        assert!(v6_alloc.allocate_specific(v4_ip).is_err());
1002    }
1003
1004    // ========================
1005    // Helper function tests
1006    // ========================
1007
1008    #[test]
1009    fn test_ipv4_add() {
1010        let base: Ipv4Addr = "10.0.0.0".parse().unwrap();
1011        assert_eq!(ipv4_add(base, 1), Some("10.0.0.1".parse().unwrap()));
1012        assert_eq!(ipv4_add(base, 256), Some("10.0.1.0".parse().unwrap()));
1013    }
1014
1015    #[test]
1016    fn test_ipv4_add_overflow() {
1017        let base: Ipv4Addr = "255.255.255.255".parse().unwrap();
1018        assert_eq!(ipv4_add(base, 1), None);
1019    }
1020
1021    #[test]
1022    fn test_ipv6_add() {
1023        let base: Ipv6Addr = "fd00::".parse().unwrap();
1024        assert_eq!(ipv6_add(base, 1), Some("fd00::1".parse().unwrap()));
1025        assert_eq!(ipv6_add(base, 0xffff), Some("fd00::ffff".parse().unwrap()));
1026    }
1027
1028    #[test]
1029    fn test_ipv6_add_overflow() {
1030        let base: Ipv6Addr = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff".parse().unwrap();
1031        assert_eq!(ipv6_add(base, 1), None);
1032    }
1033
1034    #[test]
1035    fn test_host_count_v4() {
1036        assert_eq!(host_count(false, 24), 254); // 2^8 - 2
1037        assert_eq!(host_count(false, 30), 2); // 2^2 - 2
1038        assert_eq!(host_count(false, 16), 65534); // 2^16 - 2
1039        assert_eq!(host_count(false, 31), 0); // /31 — no classical hosts
1040        assert_eq!(host_count(false, 32), 0); // /32 — single address
1041    }
1042
1043    #[test]
1044    fn test_host_count_v6() {
1045        assert_eq!(host_count(true, 126), 3); // 2^2 - 1
1046        assert_eq!(host_count(true, 127), 1); // 2^1 - 1
1047        assert_eq!(host_count(true, 128), 0); // /128 — single address (is network addr)
1048        assert_eq!(host_count(true, 64), (1u128 << 64) - 1); // 2^64 - 1
1049    }
1050
1051    // ========================
1052    // NodeSliceAllocator tests
1053    // ========================
1054
1055    fn cluster() -> IpNet {
1056        "10.200.0.0/16".parse().unwrap()
1057    }
1058
1059    #[test]
1060    fn test_slice_new_rejects_equal_prefix() {
1061        let err = NodeSliceAllocator::new(cluster(), 16).unwrap_err();
1062        assert!(matches!(err, OverlayError::InvalidCidr(_)));
1063    }
1064
1065    #[test]
1066    fn test_slice_new_rejects_smaller_prefix() {
1067        let err = NodeSliceAllocator::new(cluster(), 8).unwrap_err();
1068        assert!(matches!(err, OverlayError::InvalidCidr(_)));
1069    }
1070
1071    #[test]
1072    fn test_slice_new_rejects_over_max() {
1073        let err = NodeSliceAllocator::new(cluster(), 33).unwrap_err();
1074        assert!(matches!(err, OverlayError::InvalidCidr(_)));
1075    }
1076
1077    #[test]
1078    fn test_slice_capacity_28_in_16() {
1079        let allocator = NodeSliceAllocator::new(cluster(), 28).unwrap();
1080        // /16 → /28 ⇒ 2^12 = 4096 slices
1081        assert_eq!(allocator.capacity(), 4096);
1082    }
1083
1084    #[test]
1085    fn test_slice_capacity_24_in_16() {
1086        let allocator = NodeSliceAllocator::new(cluster(), 24).unwrap();
1087        // /16 → /24 ⇒ 2^8 = 256 slices
1088        assert_eq!(allocator.capacity(), 256);
1089    }
1090
1091    #[test]
1092    fn test_slice_assign_is_within_cluster() {
1093        let mut allocator = NodeSliceAllocator::new(cluster(), 28).unwrap();
1094        let slice = allocator.assign("node-a").unwrap();
1095        assert_eq!(slice.prefix_len(), 28);
1096        assert!(cluster().contains(&slice.network()));
1097    }
1098
1099    #[test]
1100    fn test_slice_assign_is_idempotent() {
1101        let mut allocator = NodeSliceAllocator::new(cluster(), 28).unwrap();
1102        let first = allocator.assign("node-a").unwrap();
1103        let second = allocator.assign("node-a").unwrap();
1104        assert_eq!(first, second);
1105        assert_eq!(allocator.assigned_count(), 1);
1106    }
1107
1108    #[test]
1109    fn test_slice_assign_different_nodes_get_different_slices() {
1110        let mut allocator = NodeSliceAllocator::new(cluster(), 28).unwrap();
1111        let a = allocator.assign("node-a").unwrap();
1112        let b = allocator.assign("node-b").unwrap();
1113        let c = allocator.assign("node-c").unwrap();
1114        assert_ne!(a, b);
1115        assert_ne!(b, c);
1116        assert_ne!(a, c);
1117    }
1118
1119    #[test]
1120    fn test_slice_release() {
1121        let mut allocator = NodeSliceAllocator::new(cluster(), 28).unwrap();
1122        let slice = allocator.assign("node-a").unwrap();
1123        assert_eq!(allocator.slice_for("node-a"), Some(slice));
1124
1125        assert!(allocator.release("node-a"));
1126        assert_eq!(allocator.slice_for("node-a"), None);
1127
1128        // Release of unknown node returns false.
1129        assert!(!allocator.release("node-a"));
1130    }
1131
1132    #[test]
1133    fn test_slice_collision_probes_forward() {
1134        // Use a very small cluster → few slices → high probability that two
1135        // arbitrary IDs hash to the same candidate index. Force a true collision
1136        // by manually occupying the slot a second node's hash maps to.
1137        let small: IpNet = "10.200.0.0/28".parse().unwrap();
1138        let mut allocator = NodeSliceAllocator::new(small, 30).unwrap();
1139        // /28 → /30 ⇒ 2^2 = 4 slices
1140        assert_eq!(allocator.capacity(), 4);
1141
1142        // Assign 4 nodes — all must succeed and all must land on distinct slices.
1143        let ids = ["a", "b", "c", "d"];
1144        let mut slices: Vec<IpNet> = Vec::new();
1145        for id in ids {
1146            let slice = allocator.assign(id).unwrap();
1147            assert!(
1148                !slices.contains(&slice),
1149                "slice {slice} re-assigned; all slices must be distinct"
1150            );
1151            slices.push(slice);
1152        }
1153        assert_eq!(allocator.assigned_count(), 4);
1154    }
1155
1156    #[test]
1157    fn test_slice_exhaustion_4096() {
1158        let mut allocator = NodeSliceAllocator::new(cluster(), 28).unwrap();
1159        // Fill every one of the 4096 slices.
1160        for i in 0..4096u32 {
1161            let id = format!("node-{i}");
1162            allocator.assign(&id).unwrap();
1163        }
1164        assert_eq!(allocator.assigned_count(), 4096);
1165
1166        // The next assignment must fail with NoAvailableIps.
1167        let err = allocator.assign("node-4096").unwrap_err();
1168        assert!(matches!(err, OverlayError::NoAvailableIps));
1169    }
1170
1171    #[test]
1172    fn test_slice_snapshot_roundtrip() {
1173        let mut allocator = NodeSliceAllocator::new(cluster(), 28).unwrap();
1174        let slice_a = allocator.assign("node-a").unwrap();
1175        let slice_b = allocator.assign("node-b").unwrap();
1176        let slice_c = allocator.assign("node-c").unwrap();
1177
1178        let snapshot = allocator.snapshot();
1179
1180        // Round-trip through JSON serialization too.
1181        let json = serde_json::to_string(&snapshot).unwrap();
1182        let snapshot_restored: NodeSliceAllocatorSnapshot = serde_json::from_str(&json).unwrap();
1183
1184        let restored = NodeSliceAllocator::restore(snapshot_restored).unwrap();
1185        assert_eq!(restored.slice_for("node-a"), Some(slice_a));
1186        assert_eq!(restored.slice_for("node-b"), Some(slice_b));
1187        assert_eq!(restored.slice_for("node-c"), Some(slice_c));
1188        assert_eq!(restored.capacity(), 4096);
1189        assert_eq!(restored.slice_prefix(), 28);
1190        assert_eq!(restored.cluster_cidr(), cluster());
1191    }
1192
1193    #[test]
1194    fn test_slice_restore_rejects_mismatched_prefix() {
1195        let snapshot = NodeSliceAllocatorSnapshot {
1196            cluster_cidr: "10.200.0.0/16".to_string(),
1197            slice_prefix: 28,
1198            assigned: vec![("node-a".to_string(), "10.200.0.0/24".to_string())],
1199        };
1200        let err = NodeSliceAllocator::restore(snapshot).unwrap_err();
1201        assert!(matches!(err, OverlayError::InvalidCidr(_)));
1202    }
1203
1204    #[test]
1205    fn test_slice_restore_rejects_out_of_cluster() {
1206        let snapshot = NodeSliceAllocatorSnapshot {
1207            cluster_cidr: "10.200.0.0/16".to_string(),
1208            slice_prefix: 28,
1209            assigned: vec![("node-a".to_string(), "10.201.0.0/28".to_string())],
1210        };
1211        let err = NodeSliceAllocator::restore(snapshot).unwrap_err();
1212        assert!(matches!(err, OverlayError::InvalidCidr(_)));
1213    }
1214
1215    #[test]
1216    fn test_slice_hash_is_deterministic() {
1217        // Two allocators built fresh should produce the same first-assignment
1218        // index for the same node ID — critical for consistency across leader
1219        // restart on a fresh cluster (before any snapshot exists).
1220        let mut a = NodeSliceAllocator::new(cluster(), 28).unwrap();
1221        let mut b = NodeSliceAllocator::new(cluster(), 28).unwrap();
1222        let slice_a = a.assign("my-node-id").unwrap();
1223        let slice_b = b.assign("my-node-id").unwrap();
1224        assert_eq!(slice_a, slice_b);
1225    }
1226
1227    #[test]
1228    fn test_slice_allocator_v6() {
1229        let cluster_v6: IpNet = "fd00:200::/48".parse().unwrap();
1230        let mut allocator = NodeSliceAllocator::new(cluster_v6, 64).unwrap();
1231        // /48 → /64 ⇒ 2^16 = 65536 slices
1232        assert_eq!(allocator.capacity(), 65536);
1233
1234        let slice = allocator.assign("node-a").unwrap();
1235        assert_eq!(slice.prefix_len(), 64);
1236        assert!(cluster_v6.contains(&slice.network()));
1237    }
1238}