Skip to main content

devimint/vars/
ports.rs

1use anyhow::bail;
2use fedimint_portalloc::port_alloc;
3
4/// Number of ports [`super::Global::init`] takes from its [`PortRange`] when
5/// none of them are provided explicitly (gateway base port, faucet port).
6///
7/// Keep in sync with the `ports.take(..)` calls in [`super::Global`]. A value
8/// that is too small makes devimint fail on startup.
9pub const GLOBAL_PORTS: u16 = 24;
10
11/// A contiguous range of ports reserved with a single [`port_alloc`] call and
12/// handed out one by one.
13///
14/// Each [`port_alloc`] call takes a lock shared by every test process on the
15/// machine. Reserving all ports at once keeps devimint startup from queueing
16/// on that lock once per port when many tests run in parallel.
17#[derive(Debug)]
18pub struct PortRange {
19    next: u16,
20    end: u16,
21}
22
23impl PortRange {
24    /// Reserve `size` ports with [`port_alloc`].
25    pub fn alloc(size: u16) -> anyhow::Result<Self> {
26        Ok(Self::from_base(port_alloc(size)?, size))
27    }
28
29    /// Use `size` ports starting at `base` without reserving them.
30    pub fn from_base(base: u16, size: u16) -> Self {
31        Self {
32            next: base,
33            end: base.saturating_add(size),
34        }
35    }
36
37    /// Take the next `count` contiguous ports and return the first of them.
38    pub fn take(&mut self, count: u16) -> anyhow::Result<u16> {
39        let start = self.next;
40        let Some(end) = start.checked_add(count).filter(|end| *end <= self.end) else {
41            let left = self.end - start;
42            bail!("Port range exhausted: {count} ports requested, {left} left");
43        };
44        self.next = end;
45        Ok(start)
46    }
47}
48
49#[cfg(test)]
50mod tests;