Skip to main content

orbit_cell/
text.rs

1//! Fixed-width text cells: the string arena beside the scalar table.
2//!
3//! A text cell holds up to [`CELL_TEXT_MAX`] bytes of UTF-8 in shared memory.
4//! Sixty-four bits can be swapped in one instruction; a string cannot, so a
5//! cell is a seqlock: writers take the cell's own spin bit and bump a version
6//! around their write, readers copy and accept the copy only if the version
7//! held still. Readers never block writers and never see a torn string.
8
9use std::collections::HashMap;
10use std::fmt;
11use std::str::FromStr;
12use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU32, Ordering};
13use std::sync::{Arc, LazyLock, Mutex, Weak};
14
15use orbit_core::Fleet;
16#[cfg(unix)]
17use orbit_core::shm::{ShmRegion, ring_segment_name};
18
19use crate::{Error, Result, SLOT_EMPTY, SLOT_OCCUPIED, lock_unpoisoned};
20
21/// Reserved Orbit SHM kind for the text cell table.
22pub const CELL_TEXT_KIND: u8 = 227;
23/// Number of text cells one fleet generation can hold at once.
24///
25/// Compile-time geometry: `ORBIT_CELL_TEXT_CAPACITY`. Must be a power of two.
26pub const CELL_TEXT_CAPACITY: usize =
27    orbit_core::compile::usize_from_env(option_env!("ORBIT_CELL_TEXT_CAPACITY"), 1_024);
28/// Bytes one text cell can hold.
29///
30/// Compile-time geometry: `ORBIT_CELL_TEXT_MAX`. It sizes every slot, so it is
31/// part of the same wire contract as the capacity.
32pub const CELL_TEXT_MAX: usize =
33    orbit_core::compile::usize_from_env(option_env!("ORBIT_CELL_TEXT_MAX"), 240);
34
35#[cfg(unix)]
36const TEXT_MAGIC: u32 = 0x43_54_58_54; // "CTXT"
37#[cfg(unix)]
38const TEXT_VERSION: u16 = 2;
39
40/// The address of one text cell; prints as `text:<slot>:<generation>`.
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
42pub struct TextId {
43    index: u32,
44    generation: u32,
45}
46
47impl TextId {
48    pub const fn index(self) -> u32 {
49        self.index
50    }
51
52    pub const fn generation(self) -> u32 {
53        self.generation
54    }
55
56    pub const fn to_bits(self) -> u64 {
57        ((self.index as u64) << 32) | self.generation as u64
58    }
59
60    pub const fn from_bits(bits: u64) -> Self {
61        Self {
62            index: (bits >> 32) as u32,
63            generation: bits as u32,
64        }
65    }
66}
67
68impl fmt::Display for TextId {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(f, "text:{}:{}", self.index, self.generation)
71    }
72}
73
74impl FromStr for TextId {
75    type Err = Error;
76
77    fn from_str(text: &str) -> Result<Self> {
78        let malformed = || Error::Malformed(text.to_owned());
79        let rest = text.strip_prefix("text:").ok_or_else(malformed)?;
80        let (index, generation) = rest.split_once(':').ok_or_else(malformed)?;
81        Ok(Self {
82            index: index.parse().map_err(|_| malformed())?,
83            generation: generation.parse().map_err(|_| malformed())?,
84        })
85    }
86}
87
88/// One text cell. Cheap to clone; every clone is the same place.
89#[derive(Clone)]
90pub struct Text {
91    table: TextBackend,
92    id: TextId,
93}
94
95impl Text {
96    pub fn id(&self) -> TextId {
97        self.id
98    }
99
100    /// A copy of the current text.
101    pub fn load(&self) -> Result<String> {
102        let slot = self.slot()?;
103        let mut bytes = vec![0_u8; CELL_TEXT_MAX];
104        loop {
105            let before = slot.version.load(Ordering::Acquire);
106            if before & 1 == 1 {
107                std::hint::spin_loop();
108                continue;
109            }
110            let len = usize::from(slot.len.load(Ordering::Relaxed)).min(CELL_TEXT_MAX);
111            for (target, source) in bytes[..len].iter_mut().zip(&slot.bytes[..len]) {
112                *target = source.load(Ordering::Relaxed);
113            }
114            std::sync::atomic::fence(Ordering::Acquire);
115            if slot.version.load(Ordering::Relaxed) == before {
116                bytes.truncate(len);
117                return String::from_utf8(bytes).map_err(|_| Error::Corrupt(self.id.to_string()));
118            }
119        }
120    }
121
122    pub fn len(&self) -> Result<usize> {
123        Ok(usize::from(self.slot()?.len.load(Ordering::Acquire)))
124    }
125
126    pub fn is_empty(&self) -> Result<bool> {
127        Ok(self.len()? == 0)
128    }
129
130    /// Replace the text.
131    pub fn store(&self, text: &str) -> Result<()> {
132        if text.len() > CELL_TEXT_MAX {
133            return Err(Error::TooLong {
134                len: text.len(),
135                max: CELL_TEXT_MAX,
136            });
137        }
138        let slot = self.slot()?;
139        let _write = slot.writer();
140        slot.write(0, text.as_bytes());
141        Ok(())
142    }
143
144    /// Append to the text, atomically with respect to every other writer;
145    /// refused whole, never cut, when the result would not fit.
146    pub fn append(&self, text: &str) -> Result<usize> {
147        let slot = self.slot()?;
148        let _write = slot.writer();
149        let current = usize::from(slot.len.load(Ordering::Relaxed));
150        let total = current + text.len();
151        if total > CELL_TEXT_MAX {
152            return Err(Error::TooLong {
153                len: total,
154                max: CELL_TEXT_MAX,
155            });
156        }
157        slot.write(current, text.as_bytes());
158        Ok(total)
159    }
160
161    /// Give the cell back; this and every other handle to it go stale.
162    pub fn release(self) -> Result<()> {
163        self.table.release(self.id)
164    }
165
166    /// The seqlock sequence at rest, the thing [`Self::wait_changed`] waits
167    /// on. Take it before [`Self::load`] and the wait misses nothing.
168    pub fn version(&self) -> Result<u32> {
169        let slot = self.slot()?;
170        loop {
171            let version = slot.version.load(Ordering::Acquire);
172            if version & 1 == 0 {
173                return Ok(version);
174            }
175            std::hint::spin_loop();
176        }
177    }
178
179    /// Park until the text has been written since `since`, then return the
180    /// sequence now. A released cell wakes every waiter with
181    /// [`Error::StaleText`]. Blocking; an async runtime wraps it.
182    pub fn wait_changed(&self, since: u32) -> Result<u32> {
183        loop {
184            let slot = self.slot()?;
185            let now = slot.version.load(Ordering::SeqCst);
186            if now != since {
187                if now & 1 == 1 {
188                    std::hint::spin_loop();
189                    continue;
190                }
191                return Ok(now);
192            }
193            slot.waiters.fetch_add(1, Ordering::SeqCst);
194            let outcome = if slot.version.load(Ordering::SeqCst) == since {
195                crate::wait_on(&slot.version, since)
196            } else {
197                Ok(())
198            };
199            slot.waiters.fetch_sub(1, Ordering::SeqCst);
200            outcome?;
201        }
202    }
203
204    fn slot(&self) -> Result<&TextSlot> {
205        self.table.slot(self.id)
206    }
207}
208
209#[derive(Clone)]
210pub(crate) enum TextBackend {
211    InMemory(Arc<MemoryTextTable>),
212    #[cfg(unix)]
213    Shm(Arc<ShmTextTable>),
214}
215
216impl TextBackend {
217    pub(crate) fn new(fleet: &Arc<Fleet>) -> Result<Self> {
218        Ok(if fleet.is_shm() {
219            #[cfg(unix)]
220            {
221                Self::Shm(Arc::new(ShmTextTable::open_or_create(&ring_segment_name(
222                    fleet.name(),
223                    CELL_TEXT_KIND,
224                ))?))
225            }
226            #[cfg(not(unix))]
227            unreachable!("non-Unix fleets cannot use POSIX SHM")
228        } else {
229            Self::InMemory(memory_table(fleet))
230        })
231    }
232
233    pub(crate) fn allocate(&self, text: &str) -> Result<Text> {
234        if text.len() > CELL_TEXT_MAX {
235            return Err(Error::TooLong {
236                len: text.len(),
237                max: CELL_TEXT_MAX,
238            });
239        }
240        let id = self.with_structure(|slots, hint| {
241            let capacity = slots.len();
242            let start = hint.load(Ordering::Relaxed) as usize;
243            for offset in 0..capacity {
244                let index = (start + offset) & (capacity - 1);
245                let slot = &slots[index];
246                if slot.state.load(Ordering::Acquire) == SLOT_EMPTY {
247                    let generation = slot.install(text.as_bytes());
248                    hint.store(((index + 1) & (capacity - 1)) as u32, Ordering::Relaxed);
249                    return Ok(TextId {
250                        index: index as u32,
251                        generation,
252                    });
253                }
254            }
255            Err(Error::Full { capacity })
256        })?;
257        Ok(Text {
258            table: self.clone(),
259            id,
260        })
261    }
262
263    pub(crate) fn open(&self, id: TextId) -> Result<Text> {
264        self.slot(id)?;
265        Ok(Text {
266            table: self.clone(),
267            id,
268        })
269    }
270
271    pub(crate) fn release(&self, id: TextId) -> Result<()> {
272        self.with_structure(|slots, _| {
273            let slot = slots
274                .get(id.index as usize)
275                .filter(|slot| slot.is(id))
276                .ok_or(Error::StaleText(id))?;
277            slot.state.store(SLOT_EMPTY, Ordering::Release);
278            // An even step keeps the seqlock at rest; waiters find it gone.
279            slot.version.fetch_add(2, Ordering::SeqCst);
280            slot.wake_waiters();
281            Ok(())
282        })
283    }
284
285    pub(crate) fn is_live(&self, id: TextId) -> bool {
286        self.slot(id).is_ok()
287    }
288
289    pub(crate) fn reset_all(&self) -> Result<()> {
290        self.with_structure(|slots, hint| {
291            for slot in slots {
292                slot.state.store(SLOT_EMPTY, Ordering::Release);
293                slot.version.fetch_add(2, Ordering::SeqCst);
294                slot.wake_waiters();
295            }
296            hint.store(0, Ordering::Relaxed);
297            Ok(())
298        })
299    }
300
301    #[cfg(unix)]
302    pub(crate) fn unlink(&self) -> Result<()> {
303        match self {
304            Self::InMemory(_) => self.reset_all(),
305            Self::Shm(table) => table.region.unlink().map_err(Error::Io),
306        }
307    }
308
309    fn slots(&self) -> &[TextSlot] {
310        match self {
311            Self::InMemory(table) => &table.slots,
312            #[cfg(unix)]
313            Self::Shm(table) => table.slots(),
314        }
315    }
316
317    fn slot(&self, id: TextId) -> Result<&TextSlot> {
318        self.slots()
319            .get(id.index as usize)
320            .filter(|slot| slot.is(id))
321            .ok_or(Error::StaleText(id))
322    }
323
324    fn with_structure<T>(
325        &self,
326        operation: impl FnOnce(&[TextSlot], &AtomicU32) -> Result<T>,
327    ) -> Result<T> {
328        match self {
329            Self::InMemory(table) => {
330                let _local = lock_unpoisoned(&table.structural_lock);
331                operation(&table.slots, &table.hint)
332            }
333            #[cfg(unix)]
334            Self::Shm(table) => table.with_structure(operation),
335        }
336    }
337}
338
339#[repr(C, align(64))]
340struct TextStateHeader {
341    #[cfg(unix)]
342    magic: u32,
343    #[cfg(not(unix))]
344    _magic: u32,
345    #[cfg(unix)]
346    version: u16,
347    #[cfg(not(unix))]
348    _version: u16,
349    header_size: u16,
350    capacity: u32,
351    slot_size: u32,
352    hint: AtomicU32,
353    _reserved: [u8; 44],
354}
355
356impl TextStateHeader {
357    fn new() -> Self {
358        Self {
359            #[cfg(unix)]
360            magic: TEXT_MAGIC,
361            #[cfg(not(unix))]
362            _magic: 0,
363            #[cfg(unix)]
364            version: TEXT_VERSION,
365            #[cfg(not(unix))]
366            _version: 0,
367            header_size: size_of::<Self>() as u16,
368            capacity: CELL_TEXT_CAPACITY as u32,
369            slot_size: size_of::<TextSlot>() as u32,
370            hint: AtomicU32::new(0),
371            _reserved: [0; 44],
372        }
373    }
374}
375
376/// One text cell in shared memory: a seqlock version, a writer bit, a
377/// length and the bytes, padded to the cache line.
378#[repr(C, align(64))]
379struct TextSlot {
380    state: AtomicU8,
381    writer: AtomicU8,
382    len: AtomicU16,
383    generation: AtomicU32,
384    /// The seqlock's sequence: odd while a write is in progress, and the
385    /// word a waiter parks on, since every write moves it.
386    version: AtomicU32,
387    /// Waiters parked on `version`; a writer wakes only when nonzero.
388    waiters: AtomicU32,
389    bytes: [AtomicU8; CELL_TEXT_MAX],
390}
391
392impl TextSlot {
393    fn empty() -> Self {
394        Self {
395            state: AtomicU8::new(SLOT_EMPTY),
396            writer: AtomicU8::new(0),
397            len: AtomicU16::new(0),
398            generation: AtomicU32::new(0),
399            version: AtomicU32::new(0),
400            waiters: AtomicU32::new(0),
401            bytes: std::array::from_fn(|_| AtomicU8::new(0)),
402        }
403    }
404
405    fn is(&self, id: TextId) -> bool {
406        self.state.load(Ordering::Acquire) == SLOT_OCCUPIED
407            && self.generation.load(Ordering::Relaxed) == id.generation
408    }
409
410    /// Under the structural lock.
411    fn install(&self, text: &[u8]) -> u32 {
412        let generation = self
413            .generation
414            .load(Ordering::Relaxed)
415            .wrapping_add(1)
416            .max(1);
417        for (index, byte) in self.bytes.iter().enumerate() {
418            byte.store(text.get(index).copied().unwrap_or(0), Ordering::Relaxed);
419        }
420        self.len.store(text.len() as u16, Ordering::Relaxed);
421        self.version.store(0, Ordering::Relaxed);
422        self.waiters.store(0, Ordering::Relaxed);
423        self.writer.store(0, Ordering::Relaxed);
424        self.generation.store(generation, Ordering::Relaxed);
425        self.state.store(SLOT_OCCUPIED, Ordering::Release);
426        generation
427    }
428
429    /// The cell's writer bit, held for the duration of one write.
430    fn writer(&self) -> WriterGuard<'_> {
431        while self
432            .writer
433            .compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed)
434            .is_err()
435        {
436            std::hint::spin_loop();
437        }
438        WriterGuard(self)
439    }
440
441    /// Write `bytes` at `offset` and publish the new length; the caller holds
442    /// the writer bit and has checked the fit.
443    fn write(&self, offset: usize, bytes: &[u8]) {
444        debug_assert!(offset + bytes.len() <= CELL_TEXT_MAX);
445        self.version.fetch_add(1, Ordering::AcqRel);
446        for (target, source) in self.bytes[offset..offset + bytes.len()].iter().zip(bytes) {
447            target.store(*source, Ordering::Relaxed);
448        }
449        self.len
450            .store((offset + bytes.len()) as u16, Ordering::Relaxed);
451        self.version.fetch_add(1, Ordering::SeqCst);
452        self.wake_waiters();
453    }
454
455    /// The sequence moved: wake whoever parked on it, if anyone did.
456    fn wake_waiters(&self) {
457        if self.waiters.load(Ordering::SeqCst) > 0 {
458            crate::wake_on(&self.version);
459        }
460    }
461}
462
463struct WriterGuard<'a>(&'a TextSlot);
464
465impl Drop for WriterGuard<'_> {
466    fn drop(&mut self) {
467        self.0.writer.store(0, Ordering::Release);
468    }
469}
470
471pub(crate) struct MemoryTextTable {
472    /// Held so the fleet's address, which keys the registry, cannot be
473    /// reused by another fleet while this table lives.
474    _fleet: Arc<Fleet>,
475    slots: Vec<TextSlot>,
476    hint: AtomicU32,
477    structural_lock: Mutex<()>,
478}
479
480impl MemoryTextTable {
481    fn new(fleet: Arc<Fleet>) -> Self {
482        Self {
483            _fleet: fleet,
484            slots: (0..CELL_TEXT_CAPACITY).map(|_| TextSlot::empty()).collect(),
485            hint: AtomicU32::new(0),
486            structural_lock: Mutex::new(()),
487        }
488    }
489}
490
491type MemoryRegistry = HashMap<usize, Weak<MemoryTextTable>>;
492
493static MEMORY_TABLES: LazyLock<Mutex<MemoryRegistry>> =
494    LazyLock::new(|| Mutex::new(HashMap::new()));
495
496fn memory_table(fleet: &Arc<Fleet>) -> Arc<MemoryTextTable> {
497    let fleet_identity = Arc::as_ptr(fleet) as usize;
498    let mut tables = lock_unpoisoned(&MEMORY_TABLES);
499    tables.retain(|_, table| table.strong_count() > 0);
500    if let Some(table) = tables.get(&fleet_identity).and_then(Weak::upgrade) {
501        return table;
502    }
503    let table = Arc::new(MemoryTextTable::new(Arc::clone(fleet)));
504    tables.insert(fleet_identity, Arc::downgrade(&table));
505    table
506}
507
508#[cfg(unix)]
509pub(crate) struct ShmTextTable {
510    region: ShmRegion,
511    structural_lock: Mutex<()>,
512}
513
514#[cfg(unix)]
515impl ShmTextTable {
516    fn open_or_create(name: &str) -> Result<Self> {
517        use std::{io, ptr};
518
519        let (region, _initialization_lock) =
520            ShmRegion::open_or_create_locked(name, shm_segment_size())?;
521        if region.created() {
522            unsafe {
523                ptr::write(
524                    region.as_ptr().cast::<TextStateHeader>(),
525                    TextStateHeader::new(),
526                );
527                let slots = region.as_ptr().add(size_of::<TextStateHeader>());
528                ptr::write_bytes(slots, 0, CELL_TEXT_CAPACITY * size_of::<TextSlot>());
529            }
530        } else {
531            let header = unsafe { &*region.as_ptr().cast::<TextStateHeader>() };
532            if header.magic != TEXT_MAGIC {
533                return Err(Error::Io(io::Error::new(
534                    io::ErrorKind::InvalidData,
535                    format!(
536                        "SHM segment {name} has wrong magic 0x{:08X} (expected 0x{TEXT_MAGIC:08X})",
537                        header.magic
538                    ),
539                )));
540            }
541            if header.version != TEXT_VERSION
542                || usize::from(header.header_size) != size_of::<TextStateHeader>()
543                || header.capacity as usize != CELL_TEXT_CAPACITY
544                || header.slot_size as usize != size_of::<TextSlot>()
545            {
546                return Err(Error::Io(io::Error::new(
547                    io::ErrorKind::InvalidData,
548                    format!("SHM segment {name} has an incompatible text-cell layout"),
549                )));
550            }
551        }
552        Ok(Self {
553            region,
554            structural_lock: Mutex::new(()),
555        })
556    }
557
558    fn header(&self) -> &TextStateHeader {
559        unsafe { &*self.region.as_ptr().cast::<TextStateHeader>() }
560    }
561
562    fn slots(&self) -> &[TextSlot] {
563        unsafe {
564            std::slice::from_raw_parts(
565                self.region
566                    .as_ptr()
567                    .add(size_of::<TextStateHeader>())
568                    .cast::<TextSlot>(),
569                CELL_TEXT_CAPACITY,
570            )
571        }
572    }
573
574    fn with_structure<T>(
575        &self,
576        operation: impl FnOnce(&[TextSlot], &AtomicU32) -> Result<T>,
577    ) -> Result<T> {
578        let _local = lock_unpoisoned(&self.structural_lock);
579        let _process = self.region.lock_exclusive()?;
580        operation(self.slots(), &self.header().hint)
581    }
582}
583
584#[cfg(unix)]
585fn shm_segment_size() -> usize {
586    size_of::<TextStateHeader>() + CELL_TEXT_CAPACITY * size_of::<TextSlot>()
587}
588
589const _: () = assert!(CELL_TEXT_CAPACITY.is_power_of_two());
590const _: () = assert!(CELL_TEXT_MAX > 0 && CELL_TEXT_MAX <= u16::MAX as usize);
591const _: () = assert!(size_of::<TextStateHeader>() == 64);
592// 16 bytes of fixed fields, then the text, padded to the cache line.
593const _: () = assert!(size_of::<TextSlot>() == (16 + CELL_TEXT_MAX).next_multiple_of(64));