ferravex_net/
local_link.rs

1//! Bounded, independently instantiated supplied-time datagram router.
2//!
3//! A two-peer router is a local pair; more peers use the same explicit routing.
4//! The caller supplies a nonzero, never-reused `link_id` namespace per router
5//! lifetime, and distinct peer IDs. Handles include that namespace and a private
6//! generation: reset/disposal rejects stale handles before touching queues. These
7//! identities are local routing guards, not wire authentication. Do not reuse a
8//! namespace after dropping a router while old handles might still exist.
9//!
10//! `send` success means **complete local admission**, including packets selected
11//! for later configured loss. A full queue returns an error even for such a
12//! packet. Return `send(...).is_ok()` to protocol callbacks; intentional loss is
13//! observed only by `receive`, never by inventing ACKs. Default settings are a
14//! reliable ordered queue. Periodic impairment uses the one-based accepted packet
15//! ordinal across all routes: every Nth is lost and/or gets extra reorder delay.
16//! Refusals consume no ordinal. No RNG, thread, socket or implicit clock exists.
17//!
18//! Time is monotonic, exact microsecond `Duration`, 0..=2^53 microseconds, shared
19//! across all operations/routes. Equal times are legal. Delay and extra reorder
20//! delay are independently <=60 seconds; delivery must fit the time domain.
21//! Delivery order is `(due_at, admission ordinal)` per destination, so equal
22//! times are exact FIFO even after removals. There is no head-of-line blocking
23//! across destinations. Call receive repeatedly with a host work budget; each
24//! call removes at most one due packet (including one loss record). Poll empty
25//! destinations too if they may hold losses; no background disposal occurs.
26//!
27//! Limits are aggregate payload bytes and packets, not per-peer. Empty packets
28//! reject; maximum is the existing `MAX_PACKET_BYTES` (1200). At most 64 peers,
29//! 4096 packets and 4096*1200 logical bytes may be configured; zero queue limits
30//! are valid backpressure. Construction reserves storage for all configured
31//! packet slots (each admitted packet has an initialized 1200-byte array) and
32//! peers with fallible reservation. No send/receive/reset/dispose operation allocates.
33//! Physical allocation includes metadata/padding and unused packet-array tails;
34//! the byte limit counts only initialized payload prefixes in admitted packets.
35//! Queue selection/removal and endpoint checks take bounded linear work.
36//!
37//! On an existing router, every returned error leaves time, queues, generations,
38//! ordinal and caller output unchanged. Success, including an empty receive, advances the time watermark.
39//! A short receive output rejects before dequeue; success copies only `len`
40//! bytes, preserving its tail. A loss record or empty receive writes nothing.
41//! Reset clears all traffic/ordinals and invalidates every live handle, while
42//! preserving limits, impairment and monotonic time. Endpoint reset clears both
43//! directions for that peer and invalidates its handles; other peers/ordinals
44//! remain intact. Dispose permanently removes that peer and its traffic. Drop
45//! disposes the whole router. Generation/ordinal exhaustion never wraps.
46//!
47//! ```
48//! use ferravex_net::local_link::{LocalLink, Limits, Impairment};
49//! use std::time::Duration;
50//! let mut pair = LocalLink::new(42, &[10, 20], Limits::default(), Impairment::default())?;
51//! let a = pair.endpoint(10)?;
52//! let b = pair.endpoint(20)?;
53//! pair.send(a, b, b"whole datagram", Duration::ZERO)?;
54//! let mut output = [0xAA; 1200];
55//! let delivery = pair.receive(b, Duration::ZERO, &mut output)?.unwrap();
56//! assert!(!delivery.lost);
57//! assert_eq!(&output[..delivery.len], b"whole datagram");
58//! assert_eq!(output[delivery.len], 0xAA);
59//! pair.reset(Duration::ZERO)?;
60//! assert!(pair.send(a, b, b"stale", Duration::ZERO).is_err());
61//! # Ok::<(), ferravex_net::local_link::LinkError>(())
62//! ```
63use crate::MAX_PACKET_BYTES;
64use std::time::Duration;
65
66const MAX_PEERS: usize = 64;
67const MAX_PACKETS: usize = 4096;
68const MAX_TIME: Duration = Duration::from_micros(1 << 53);
69
70/// Aggregate queue budgets. Defaults: 128 packets and 153600 payload bytes.
71/// Both limits apply independently, including to later loss records. Bytes need
72/// not equal packets * 1200; a smaller byte cap is useful for mixed packet sizes.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct Limits {
75    /// Maximum admitted datagrams, inclusive; 0..=4096.
76    pub packets: usize,
77    /// Maximum sum of admitted payload lengths, inclusive; 0..=4915200.
78    pub bytes: usize,
79}
80impl Default for Limits {
81    fn default() -> Self {
82        Self {
83            packets: 128,
84            bytes: 128 * MAX_PACKET_BYTES,
85        }
86    }
87}
88
89/// Deterministic periodic impairment; defaults disable all impairment.
90/// `Some(0)` is invalid. Delay is applied to every packet; reorder_delay is
91/// additionally applied to every reorder_every-th admitted packet. Loss and
92/// reorder selections may overlap. Periods are global to this router, not flows.
93#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
94pub struct Impairment {
95    pub delay: Duration,
96    pub loss_every: Option<u64>,
97    pub reorder_every: Option<u64>,
98    pub reorder_delay: Duration,
99}
100
101/// Explicit peer identity within one live router generation. Use accessors for
102/// host address mapping; handles cannot be constructed with a guessed generation.
103#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
104pub struct Endpoint {
105    link_id: u64,
106    peer_id: u64,
107    generation: u64,
108}
109impl Endpoint {
110    pub fn link_id(self) -> u64 {
111        self.link_id
112    }
113    pub fn peer_id(self) -> u64 {
114        self.peer_id
115    }
116    pub fn generation(self) -> u64 {
117        self.generation
118    }
119}
120
121/// One removed due datagram. `lost=true` is a post-admission impairment record:
122/// output was untouched and must not be passed to a protocol driver.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub struct Delivery {
125    pub from: Endpoint,
126    pub to: Endpoint,
127    pub len: usize,
128    pub admitted_at: Duration,
129    pub due_at: Duration,
130    pub ordinal: u64,
131    pub lost: bool,
132}
133
134/// Preflight failures; none mutate the router or caller output.
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136#[non_exhaustive]
137pub enum LinkError {
138    InvalidLimits,
139    InvalidImpairment,
140    InvalidIdentity,
141    UnknownPeer,
142    StaleEndpoint,
143    SameEndpoint,
144    EmptyPacket,
145    PacketTooLarge,
146    PacketCapacity,
147    ByteCapacity,
148    InvalidTime,
149    BackwardsTime,
150    DeliveryTimeOverflow,
151    OutputTooSmall { required: usize },
152    Exhausted,
153    AllocationFailed,
154}
155impl std::fmt::Display for LinkError {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        write!(f, "local datagram link: {self:?}")
158    }
159}
160impl std::error::Error for LinkError {}
161
162struct Peer {
163    id: u64,
164    generation: u64,
165    active: bool,
166}
167struct Packet {
168    delivery: Delivery,
169    bytes: [u8; MAX_PACKET_BYTES],
170}
171
172/// Bounded datagram storage; no global/shared transport state or implicit I/O.
173/// See the module recipe and FPS `local_session` example for driver composition.
174pub struct LocalLink {
175    link_id: u64,
176    peers: Vec<Peer>,
177    packets: Vec<Packet>,
178    bytes: usize,
179    limits: Limits,
180    impairment: Impairment,
181    ordinal: u64,
182    now: Duration,
183}
184impl LocalLink {
185    /// Reserve the complete configured storage. Peer IDs may be zero but must be
186    /// distinct; link_id must be nonzero and lifetime-unique in the host.
187    pub fn new(
188        link_id: u64,
189        peers: &[u64],
190        limits: Limits,
191        impairment: Impairment,
192    ) -> Result<Self, LinkError> {
193        if link_id == 0
194            || peers.len() < 2
195            || peers.len() > MAX_PEERS
196            || peers
197                .iter()
198                .enumerate()
199                .any(|(i, p)| peers[..i].contains(p))
200        {
201            return Err(LinkError::InvalidIdentity);
202        }
203        if limits.packets > MAX_PACKETS || limits.bytes > MAX_PACKETS * MAX_PACKET_BYTES {
204            return Err(LinkError::InvalidLimits);
205        }
206        if impairment.loss_every == Some(0)
207            || impairment.reorder_every == Some(0)
208            || [impairment.delay, impairment.reorder_delay]
209                .iter()
210                .any(|d| *d > Duration::from_secs(60) || !d.subsec_nanos().is_multiple_of(1000))
211        {
212            return Err(LinkError::InvalidImpairment);
213        }
214        let mut endpoints = Vec::new();
215        endpoints
216            .try_reserve_exact(peers.len())
217            .map_err(|_| LinkError::AllocationFailed)?;
218        endpoints.extend(peers.iter().map(|&id| Peer {
219            id,
220            generation: 1,
221            active: true,
222        }));
223        let mut packets = Vec::new();
224        packets
225            .try_reserve_exact(limits.packets)
226            .map_err(|_| LinkError::AllocationFailed)?;
227        Ok(Self {
228            link_id,
229            peers: endpoints,
230            packets,
231            bytes: 0,
232            limits,
233            impairment,
234            ordinal: 0,
235            now: Duration::ZERO,
236        })
237    }
238    pub fn limits(&self) -> Limits {
239        self.limits
240    }
241    pub fn impairment(&self) -> Impairment {
242        self.impairment
243    }
244    pub fn queued_packets(&self) -> usize {
245        self.packets.len()
246    }
247    pub fn queued_bytes(&self) -> usize {
248        self.bytes
249    }
250    pub fn endpoint(&self, peer_id: u64) -> Result<Endpoint, LinkError> {
251        let p = self
252            .peers
253            .iter()
254            .find(|p| p.id == peer_id && p.active)
255            .ok_or(LinkError::UnknownPeer)?;
256        Ok(Endpoint {
257            link_id: self.link_id,
258            peer_id,
259            generation: p.generation,
260        })
261    }
262    fn peer_index(&self, endpoint: Endpoint) -> Result<usize, LinkError> {
263        if endpoint.link_id != self.link_id {
264            return Err(LinkError::StaleEndpoint);
265        }
266        self.peers
267            .iter()
268            .position(|p| {
269                p.active && p.id == endpoint.peer_id && p.generation == endpoint.generation
270            })
271            .ok_or(LinkError::StaleEndpoint)
272    }
273    fn check_time(&self, now: Duration) -> Result<(), LinkError> {
274        if now > MAX_TIME || !now.subsec_nanos().is_multiple_of(1000) {
275            return Err(LinkError::InvalidTime);
276        }
277        if now < self.now {
278            return Err(LinkError::BackwardsTime);
279        }
280        Ok(())
281    }
282    /// Admit one complete opaque datagram. Bytes need not be a valid protocol
283    /// packet: codecs/drivers retain that responsibility. Errors never consume an
284    /// impairment ordinal, capacity or time. Same-peer sends reject.
285    pub fn send(
286        &mut self,
287        from: Endpoint,
288        to: Endpoint,
289        bytes: &[u8],
290        now: Duration,
291    ) -> Result<(), LinkError> {
292        self.check_time(now)?;
293        self.peer_index(from)?;
294        self.peer_index(to)?;
295        if from == to {
296            return Err(LinkError::SameEndpoint);
297        }
298        if bytes.is_empty() {
299            return Err(LinkError::EmptyPacket);
300        }
301        if bytes.len() > MAX_PACKET_BYTES {
302            return Err(LinkError::PacketTooLarge);
303        }
304        if self.packets.len() == self.limits.packets {
305            return Err(LinkError::PacketCapacity);
306        }
307        if bytes.len() > self.limits.bytes - self.bytes {
308            return Err(LinkError::ByteCapacity);
309        }
310        let ordinal = self.ordinal.checked_add(1).ok_or(LinkError::Exhausted)?;
311        let selected = |period: Option<u64>| period.is_some_and(|n| ordinal.is_multiple_of(n));
312        let delay = self.impairment.delay
313            + if selected(self.impairment.reorder_every) {
314                self.impairment.reorder_delay
315            } else {
316                Duration::ZERO
317            };
318        let due_at = now
319            .checked_add(delay)
320            .filter(|t| *t <= MAX_TIME)
321            .ok_or(LinkError::DeliveryTimeOverflow)?;
322        let mut packet = Packet {
323            delivery: Delivery {
324                from,
325                to,
326                len: bytes.len(),
327                admitted_at: now,
328                due_at,
329                ordinal,
330                lost: selected(self.impairment.loss_every),
331            },
332            bytes: [0; MAX_PACKET_BYTES],
333        };
334        packet.bytes[..bytes.len()].copy_from_slice(bytes);
335        self.packets.push(packet);
336        self.bytes += bytes.len();
337        self.ordinal = ordinal;
338        self.now = now;
339        Ok(())
340    }
341    /// Remove at most one due packet for this destination. Short output rejects
342    /// without removing even a loss record; empty/lost output stays unchanged.
343    /// Work scans <=4096 slots and moves at most one slot (swap removal).
344    /// A loss still consumes its admitted packet/byte capacity until removed.
345    pub fn receive(
346        &mut self,
347        to: Endpoint,
348        now: Duration,
349        output: &mut [u8],
350    ) -> Result<Option<Delivery>, LinkError> {
351        self.check_time(now)?;
352        self.peer_index(to)?;
353        let index = self
354            .packets
355            .iter()
356            .enumerate()
357            .filter(|(_, p)| p.delivery.to == to && p.delivery.due_at <= now)
358            .min_by_key(|(_, p)| (p.delivery.due_at, p.delivery.ordinal))
359            .map(|(i, _)| i);
360        let Some(index) = index else {
361            self.now = now;
362            return Ok(None);
363        };
364        let delivery = self.packets[index].delivery;
365        if output.len() < delivery.len {
366            return Err(LinkError::OutputTooSmall {
367                required: delivery.len,
368            });
369        }
370        let packet = self.packets.swap_remove(index);
371        if !delivery.lost {
372            output[..delivery.len].copy_from_slice(&packet.bytes[..delivery.len]);
373        }
374        self.bytes -= delivery.len;
375        self.now = now;
376        Ok(Some(delivery))
377    }
378    fn discard_peer(&mut self, peer: Endpoint) {
379        self.packets
380            .retain(|p| p.delivery.from != peer && p.delivery.to != peer);
381        self.bytes = self.packets.iter().map(|p| p.delivery.len).sum();
382    }
383    /// Invalidate one endpoint and cancel both directions, preserving time and
384    /// the global impairment ordinal. The returned handle is the only fresh one.
385    ///
386    /// ```
387    /// use ferravex_net::local_link::{LocalLink, Limits, Impairment};
388    /// use std::time::Duration;
389    /// let mut link = LocalLink::new(77, &[1, 2], Limits::default(), Impairment::default())?;
390    /// let old = link.endpoint(1)?;
391    /// let fresh = link.reset_endpoint(old, Duration::ZERO)?;
392    /// assert_ne!(old, fresh);
393    /// link.dispose(fresh, Duration::ZERO)?;
394    /// assert!(link.endpoint(1).is_err());
395    /// # Ok::<(), ferravex_net::local_link::LinkError>(())
396    /// ```
397    pub fn reset_endpoint(&mut self, peer: Endpoint, now: Duration) -> Result<Endpoint, LinkError> {
398        self.check_time(now)?;
399        let i = self.peer_index(peer)?;
400        let generation = self.peers[i]
401            .generation
402            .checked_add(1)
403            .ok_or(LinkError::Exhausted)?;
404        self.discard_peer(peer);
405        self.peers[i].generation = generation;
406        self.now = now;
407        self.endpoint(peer.peer_id)
408    }
409    /// Permanently remove a peer and all its traffic. Repeated disposal rejects.
410    pub fn dispose(&mut self, peer: Endpoint, now: Duration) -> Result<(), LinkError> {
411        self.check_time(now)?;
412        let i = self.peer_index(peer)?;
413        self.discard_peer(peer);
414        self.peers[i].active = false;
415        self.now = now;
416        Ok(())
417    }
418    /// Clear traffic and reset impairment ordinal, invalidating all live handles.
419    /// Disposed peers stay disposed; time cannot be rewound or re-originated.
420    pub fn reset(&mut self, now: Duration) -> Result<(), LinkError> {
421        self.check_time(now)?;
422        if self
423            .peers
424            .iter()
425            .any(|p| p.active && p.generation == u64::MAX)
426        {
427            return Err(LinkError::Exhausted);
428        }
429        for p in &mut self.peers {
430            if p.active {
431                p.generation += 1;
432            }
433        }
434        self.packets.clear();
435        self.bytes = 0;
436        self.ordinal = 0;
437        self.now = now;
438        Ok(())
439    }
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445    #[test]
446    fn exhaustion_never_wraps_or_cancels_retained_traffic() {
447        let mut link =
448            LocalLink::new(1, &[1, 2], Limits::default(), Impairment::default()).unwrap();
449        let a = link.endpoint(1).unwrap();
450        let b = link.endpoint(2).unwrap();
451        link.send(a, b, b"retained", Duration::ZERO).unwrap();
452        link.ordinal = u64::MAX;
453        assert_eq!(
454            link.send(a, b, b"x", Duration::ZERO),
455            Err(LinkError::Exhausted)
456        );
457        link.peers[0].generation = u64::MAX;
458        let a = link.endpoint(1).unwrap();
459        assert_eq!(
460            link.reset_endpoint(a, Duration::ZERO),
461            Err(LinkError::Exhausted)
462        );
463        assert_eq!(link.reset(Duration::ZERO), Err(LinkError::Exhausted));
464        assert_eq!(link.queued_bytes(), 8);
465    }
466}