Skip to main content

orbit_link/
lib.rs

1//! Named, bounded same-host dispatch links between members of an Orbit fleet.
2//!
3//! A link combines two existing transport shapes:
4//!
5//! - one lossless inbox lane per fleet member for application-defined frames;
6//! - one [`orbit_stream`] table for the duplex byte flow attached to a frame.
7//!
8//! The inbox is admission and discovery, not a retained event log: a full
9//! lane refuses a frame instead of overwriting one, and a lane with no live
10//! owner refuses it instead of accepting work nobody can answer. The stream
11//! ticket travels inside the caller's frame, so this crate chooses no HTTP,
12//! RPC, invocation or resource-lease encoding.
13//!
14//! The fleet name is the rendezvous. No descriptor is inherited or passed,
15//! and application bytes remain in SHM. This is not an upstream protocol and
16//! it does not own a connection pool. A caller may retain and rearm a stream
17//! slot, which reuses bounded SHM capacity rather than a TCP connection or its
18//! TLS/protocol state.
19
20use std::fmt;
21
22use orbit_stream::StreamSpec;
23
24mod admission;
25#[cfg(unix)]
26mod bell;
27mod body;
28#[cfg(unix)]
29mod control;
30#[cfg(all(unix, feature = "events"))]
31pub mod events;
32mod frame;
33mod inbox;
34#[cfg(unix)]
35mod probe;
36#[cfg(all(unix, feature = "tokio"))]
37mod receiver;
38#[cfg(unix)]
39mod segment;
40#[cfg(all(unix, feature = "tokio"))]
41mod watcher;
42
43pub use admission::WorkTicket;
44#[cfg(unix)]
45pub use admission::{WorkExecution, WorkReservation};
46pub use body::LinkBodies;
47#[cfg(unix)]
48pub use control::{
49    ExchangeControl, ExchangeControlState, ExchangeControlTicket,
50    ExchangeControls,
51};
52#[cfg(all(unix, feature = "events"))]
53pub use events::{LinkEvents, Routing};
54pub use frame::{EVENT_FRAME_TAG, RESERVED_FRAME_TAGS, is_reserved};
55pub use inbox::{
56    Admission, GrowthPolicy, Inbox, InboxGeometry, LANE_NAME_MAX,
57    LANE_ROLE_MAX, Reclaimed,
58};
59#[cfg(unix)]
60pub use orbit_core::shm::GroupAccess;
61#[cfg(all(unix, feature = "probe"))]
62pub use probe::{BellCounts, bell_counts};
63#[cfg(all(unix, feature = "tokio", feature = "probe"))]
64pub use probe::{LaneCounts, LaneProbe};
65#[cfg(all(unix, feature = "tokio"))]
66pub use receiver::{InboxReceiver, Received};
67#[cfg(unix)]
68pub use segment::{Joined, LinkSegment, LinkSegmentHandle, check_name};
69#[cfg(all(unix, feature = "tokio"))]
70pub use watcher::{DirectoryWatcher, Watched};
71
72pub type Result<T, E = Error> = std::result::Result<T, E>;
73
74/// Physical resources one named link fleet opens.
75///
76/// Kinds are supplied by the deployment and must be distinct. `orbit-link`
77/// reserves no global default because several independent links may coexist
78/// in one fleet namespace.
79#[derive(Clone, Copy, Debug, Eq, PartialEq)]
80pub struct LinkSpec {
81    pub fleet_capacity: u16,
82    pub inbox_kind: u8,
83    pub inbox: InboxGeometry,
84    pub streams: StreamSpec,
85}
86
87impl LinkSpec {
88    pub const fn new(
89        fleet_capacity: u16,
90        inbox_kind: u8,
91        inbox: InboxGeometry,
92        streams: StreamSpec,
93    ) -> Self {
94        Self { fleet_capacity, inbox_kind, inbox, streams }
95    }
96
97    pub const fn inbox_segment_bytes(self) -> usize {
98        self.inbox.segment_bytes(self.fleet_capacity as usize)
99    }
100
101    fn validate(self) -> Result<()> {
102        if self.fleet_capacity == 0 {
103            return Err(Error::Malformed(
104                "link fleet capacity must not be zero",
105            ));
106        }
107        if self.inbox_kind == self.streams.kind {
108            return Err(Error::Malformed(
109                "link inbox and stream table need distinct SHM kinds",
110            ));
111        }
112        self.inbox.validate()
113    }
114}
115
116/// What can fail before a protocol adapter owns a dispatched frame.
117#[derive(Debug)]
118#[non_exhaustive]
119pub enum Error {
120    /// All receiver-declared work admissions are occupied.
121    CapacityFull,
122    /// The work reservation was cancelled, accepted, completed or replaced.
123    StaleWork,
124    /// No joined receiver owns this destination.
125    NoConsumer,
126    InboxFull,
127    InboxContended,
128    /// Every record of this producer names a frame its reader has not taken
129    /// yet, on any lane. The target lane may have room; wait with
130    /// `LinkSegment::record_released` and write again.
131    ProducerBusy,
132    NoLane,
133    NoWatcher,
134    FrameTooLarge,
135    Malformed(&'static str),
136    InvalidName {
137        name: String,
138        reason: String,
139    },
140    RoleConflict {
141        name: String,
142        role: String,
143        held_by: String,
144        lane: usize,
145        pid: u32,
146    },
147    Io(std::io::Error),
148    Core(orbit_core::Error),
149    Stream(orbit_stream::Error),
150    #[cfg(feature = "events")]
151    Events(orbit_events::Error),
152}
153
154impl fmt::Display for Error {
155    fn fmt(
156        &self,
157        formatter: &mut fmt::Formatter<'_>,
158    ) -> fmt::Result {
159        match self {
160            Self::CapacityFull => {
161                formatter.write_str("receiver work capacity is full")
162            }
163            Self::StaleWork => {
164                formatter.write_str("work reservation is no longer valid")
165            }
166            Self::NoConsumer => {
167                formatter.write_str("the receiver is not joined")
168            }
169            Self::InboxFull => {
170                formatter.write_str("the target inbox lane is full or unowned")
171            }
172            Self::InboxContended => {
173                formatter.write_str("the target inbox claim is contended")
174            }
175            Self::ProducerBusy => formatter.write_str(
176                "every frame this producer may hold unread is still unread",
177            ),
178            Self::NoLane => {
179                formatter.write_str("every lane in the named fleet is held")
180            }
181            Self::NoWatcher => formatter.write_str(
182                "every directory watcher slot in the named fleet is held",
183            ),
184            Self::FrameTooLarge => {
185                formatter.write_str("the frame does not fit in one inbox slot")
186            }
187            Self::Malformed(message) => formatter.write_str(message),
188            Self::InvalidName { name, reason } => {
189                write!(formatter, "{name:?} cannot name a link fleet: {reason}")
190            }
191            Self::RoleConflict { name, role, held_by, lane, pid } => write!(
192                formatter,
193                "{name:?} is already served by {held_by} on lane {lane} (pid {pid}); role {role:?} cannot join under the same name"
194            ),
195            Self::Io(error) => {
196                write!(formatter, "Orbit link IO error: {error}")
197            }
198            Self::Core(error) => {
199                write!(formatter, "Orbit link core error: {error}")
200            }
201            Self::Stream(error) => {
202                write!(formatter, "Orbit link stream error: {error}")
203            }
204            #[cfg(feature = "events")]
205            Self::Events(error) => {
206                write!(formatter, "Orbit link event error: {error}")
207            }
208        }
209    }
210}
211
212impl std::error::Error for Error {
213    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
214        match self {
215            Self::Io(error) => Some(error),
216            Self::Core(error) => Some(error),
217            Self::Stream(error) => Some(error),
218            #[cfg(feature = "events")]
219            Self::Events(error) => Some(error),
220            _ => None,
221        }
222    }
223}
224
225impl From<std::io::Error> for Error {
226    fn from(error: std::io::Error) -> Self {
227        Self::Io(error)
228    }
229}
230
231impl From<orbit_core::Error> for Error {
232    fn from(error: orbit_core::Error) -> Self {
233        Self::Core(error)
234    }
235}
236
237impl From<orbit_stream::Error> for Error {
238    fn from(error: orbit_stream::Error) -> Self {
239        Self::Stream(error)
240    }
241}
242
243/// Whether this host can park an inbox reader without polling.
244pub fn parking_supported() -> bool {
245    orbit_core::sync::supported()
246}