Skip to main content

orbit_atomic/
lib.rs

1//! `std::sync::atomic` between the processes of a fleet.
2//!
3//! [`Orbitals`] is one fleet-shared table of 64-bit values in Orbit shared
4//! memory. [`Orbitals::allocate`] declares a value and returns an
5//! [`Orbital`], a handle with the operations of an atomic. Its
6//! [`OrbitalId`] is the only thing that travels: any process of the fleet
7//! that [`Orbitals::open`]s the id holds the same value, and can
8//! [`Orbital::wait`] for it to change.
9//!
10//! A value lives as long as its table's shared memory. Nothing releases a
11//! single value; the table's owner clears all of them with
12//! [`Orbitals::reset_all`] when it boots with nothing else attached.
13
14use std::sync::Arc;
15use std::sync::atomic::AtomicU32;
16
17use orbit_core::Fleet;
18#[cfg(unix)]
19use orbit_core::shm::ring_segment_name;
20
21mod error;
22mod id;
23mod orbital;
24mod table;
25mod wake;
26
27pub use error::{Error, Result};
28pub use id::{Kind, OrbitalId, Primitive};
29pub use orbital::Orbital;
30pub use table::{ATOMIC_CAPACITY, ATOMIC_KIND};
31
32use table::Table;
33
34/// Whether this build can park on a shared word. A table refuses to open
35/// where it cannot: a sleep loop wearing the shape of a wait is worse than
36/// a clear no.
37#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
38fn waits_supported() -> bool {
39    orbit_core::sync::supported()
40}
41
42#[cfg(not(any(
43    target_os = "linux",
44    target_os = "freebsd",
45    target_os = "macos"
46)))]
47fn waits_supported() -> bool {
48    false
49}
50
51/// Park until `word` no longer holds `expected`, through the platform's
52/// shared address wait. There is no polling fallback: a table refuses to
53/// open where the platform cannot wait, so by here it can.
54#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
55pub(crate) fn wait_on(
56    word: &AtomicU32,
57    expected: u32,
58) -> Result<()> {
59    orbit_core::sync::wait_word(word, expected).map_err(Error::Io)
60}
61
62#[cfg(not(any(
63    target_os = "linux",
64    target_os = "freebsd",
65    target_os = "macos"
66)))]
67pub(crate) fn wait_on(
68    _word: &AtomicU32,
69    _expected: u32,
70) -> Result<()> {
71    Err(unsupported())
72}
73
74/// Wake everyone parked on `word`; nothing to do where nobody can park.
75pub(crate) fn wake_on(word: &AtomicU32) {
76    #[cfg(any(
77        target_os = "linux",
78        target_os = "freebsd",
79        target_os = "macos"
80    ))]
81    let _ = orbit_core::sync::wake_word(word);
82    #[cfg(not(any(
83        target_os = "linux",
84        target_os = "freebsd",
85        target_os = "macos"
86    )))]
87    let _ = word;
88}
89
90fn unsupported() -> Error {
91    Error::Io(std::io::Error::new(
92        std::io::ErrorKind::Unsupported,
93        "orbit-atomic needs a platform that can wait on a shared word: Linux, FreeBSD, or macOS 14.4 or later",
94    ))
95}
96
97/// The fleet's table of shared values. Cheap to clone.
98#[derive(Clone)]
99pub struct Orbitals {
100    table: Arc<Table>,
101}
102
103impl Orbitals {
104    /// Attach to the fleet's table, creating it when this is the first
105    /// process to ask. An in-memory fleet gets a table on the heap, shared
106    /// by everything that holds the same fleet.
107    pub fn new(fleet: Arc<Fleet>) -> Result<Self> {
108        if !waits_supported() {
109            return Err(unsupported());
110        }
111        let table = if fleet.is_shm() {
112            #[cfg(unix)]
113            {
114                table::shm_table(&ring_segment_name(fleet.name(), ATOMIC_KIND))?
115            }
116            #[cfg(not(unix))]
117            unreachable!("non-Unix fleets cannot use POSIX SHM")
118        } else {
119            table::memory_table(&fleet)
120        };
121        Ok(Self { table })
122    }
123
124    /// Declare a value holding `initial`. The id inside the handle is what
125    /// other processes open.
126    ///
127    /// The slot is not given back until the table is reset, so the
128    /// capacity counts declarations, not live values: declare a value once
129    /// and keep it, as a `static`, rather than one per request.
130    pub fn allocate<T: Primitive>(
131        &self,
132        initial: T,
133    ) -> Result<Orbital<T>> {
134        let (id, slot) = self.table.allocate(T::KIND, initial.into_word())?;
135        Ok(Orbital::new(slot, id, Arc::clone(&self.table)))
136    }
137
138    /// A handle to the value `id` names. An id of another type is
139    /// [`Error::KindMismatch`]; an id this table did not mint, or minted
140    /// before its last reset, is [`Error::Stale`].
141    pub fn open<T: Primitive>(
142        &self,
143        id: OrbitalId,
144    ) -> Result<Orbital<T>> {
145        let slot = self.table.open(id, T::KIND)?;
146        Ok(Orbital::new(slot, id, Arc::clone(&self.table)))
147    }
148
149    /// Empty the table and start a new epoch, after which every earlier id
150    /// is stale.
151    ///
152    /// For the table's owner, at a boot where no other process is attached
153    /// and no handle is in use. A handle kept across a reset still points
154    /// at its slot, which the next allocation may hand to someone else.
155    pub fn reset_all(&self) -> Result<()> {
156        self.table.reset()
157    }
158
159    /// Remove the table's SHM object. Existing mappings remain valid until
160    /// their processes drop them.
161    #[cfg(unix)]
162    pub fn unlink(&self) -> Result<()> {
163        self.table.unlink()
164    }
165}