1use 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#[derive(Debug, Clone)]
18pub struct IpAllocator {
19 network: IpNet,
21 allocated: HashSet<IpAddr>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct IpAllocatorState {
28 pub cidr: String,
30 pub allocated: Vec<IpAddr>,
32}
33
34fn 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
42fn 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 u128::MAX
54 } else if bits == 0 {
55 0
57 } else {
58 (1u128 << bits) - 1
60 }
61 } else {
62 let bits = 32 - u32::from(prefix_len);
63 if bits <= 1 {
64 0
66 } else {
67 (1u128 << bits) - 2
69 }
70 }
71}
72
73impl IpAllocator {
74 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 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 #[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 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 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 pub fn allocate(&mut self) -> Option<IpAddr> {
164 match self.network {
165 IpNet::V4(v4net) => {
166 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 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 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 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 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 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 pub fn release(&mut self, ip: IpAddr) -> bool {
272 self.allocated.remove(&ip)
273 }
274
275 #[must_use]
277 pub fn is_allocated(&self, ip: IpAddr) -> bool {
278 self.allocated.contains(&ip)
279 }
280
281 #[must_use]
283 pub fn contains(&self, ip: IpAddr) -> bool {
284 self.network.contains(&ip)
285 }
286
287 #[must_use]
289 pub fn allocated_count(&self) -> usize {
290 self.allocated.len()
291 }
292
293 #[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 if count > u128::from(u32::MAX) {
303 u32::MAX
304 } else {
305 count as u32
306 }
307 }
308
309 #[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 #[must_use]
319 pub fn cidr(&self) -> String {
320 self.network.to_string()
321 }
322
323 #[must_use]
325 pub fn network_addr(&self) -> IpAddr {
326 self.network.network()
327 }
328
329 #[must_use]
333 pub fn broadcast_addr(&self) -> IpAddr {
334 self.network.broadcast()
335 }
336
337 #[must_use]
339 pub fn prefix_len(&self) -> u8 {
340 self.network.prefix_len()
341 }
342
343 #[must_use]
345 pub fn host_prefix_len(&self) -> u8 {
346 self.network.max_prefix_len()
347 }
348
349 #[must_use]
351 pub fn allocated_ips(&self) -> Vec<IpAddr> {
352 self.allocated.iter().copied().collect()
353 }
354}
355
356#[derive(Debug, Clone)]
368pub struct NodeSliceAllocator {
369 cluster_cidr: IpNet,
370 slice_prefix: u8,
371 assigned: HashMap<String, IpNet>,
372}
373
374#[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
382fn 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 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 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 pub fn release(&mut self, node_id: &str) -> bool {
466 self.assigned.remove(node_id).is_some()
467 }
468
469 #[must_use]
471 pub fn slice_for(&self, node_id: &str) -> Option<IpNet> {
472 self.assigned.get(node_id).copied()
473 }
474
475 #[must_use]
477 pub fn assigned_count(&self) -> usize {
478 self.assigned.len()
479 }
480
481 #[must_use]
483 pub fn capacity(&self) -> u64 {
484 self.num_slices()
485 }
486
487 #[must_use]
489 pub fn cluster_cidr(&self) -> IpNet {
490 self.cluster_cidr
491 }
492
493 #[must_use]
495 pub fn slice_prefix(&self) -> u8 {
496 self.slice_prefix
497 }
498
499 #[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 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 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 #[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
583pub 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 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 #[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 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 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 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 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 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 let allocator = IpAllocator::new("10.200.0.0/24").unwrap();
724 assert_eq!(allocator.total_hosts(), 254);
725
726 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 #[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 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 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 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 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 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 let allocator = IpAllocator::new("fd00::/126").unwrap();
884 assert_eq!(allocator.total_hosts(), 3);
885
886 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 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 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 #[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 #[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); assert_eq!(host_count(false, 30), 2); assert_eq!(host_count(false, 16), 65534); assert_eq!(host_count(false, 31), 0); assert_eq!(host_count(false, 32), 0); }
1042
1043 #[test]
1044 fn test_host_count_v6() {
1045 assert_eq!(host_count(true, 126), 3); assert_eq!(host_count(true, 127), 1); assert_eq!(host_count(true, 128), 0); assert_eq!(host_count(true, 64), (1u128 << 64) - 1); }
1050
1051 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 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 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 assert!(!allocator.release("node-a"));
1130 }
1131
1132 #[test]
1133 fn test_slice_collision_probes_forward() {
1134 let small: IpNet = "10.200.0.0/28".parse().unwrap();
1138 let mut allocator = NodeSliceAllocator::new(small, 30).unwrap();
1139 assert_eq!(allocator.capacity(), 4);
1141
1142 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 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 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 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 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 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}