Skip to main content

orbit_stream/exchange/
arena.rs

1use std::collections::HashMap;
2use std::mem::size_of;
3use std::ops::Deref;
4use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering};
5use std::sync::{Arc, LazyLock, Mutex, Weak};
6use std::task::{Context, Poll, Waker};
7
8use orbit_core::Fleet;
9#[cfg(unix)]
10use orbit_core::shm::{ShmRegion, ring_segment_name};
11
12use super::{ChunkDescriptor, ChunkGeometry, ChunkPlan, DEFAULT_CHUNK_BYTES};
13use crate::wake::{Doorstep, Driver};
14use crate::{Error, Incarnation, Result, lock_unpoisoned};
15
16const MAGIC: u32 = 0x4F_50_41_59; // "OPAY"
17const VERSION: u16 = 4;
18
19const SLOT_FREE: u8 = 0;
20const SLOT_RESERVED: u8 = 1;
21const SLOT_LIVE: u8 = 2;
22const SLOT_READING: u8 = 3;
23const SLOT_RECLAIMING: u8 = 4;
24
25/// Geometry and SHM identity of one fleet-wide payload arena.
26#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
27pub struct PayloadArenaSpec {
28    pub kind: u8,
29    /// Physical allocation units available to each fleet node.
30    pub slots_per_node: usize,
31    /// Bytes in one physical allocation unit.
32    pub slot_size: usize
33}
34
35impl PayloadArenaSpec {
36    pub const fn new(
37        kind: u8,
38        slots_per_node: usize,
39        slot_size: usize
40    ) -> Self {
41        Self { kind, slots_per_node, slot_size }
42    }
43
44    pub const fn lane_bytes(self) -> usize {
45        self.slots_per_node * self.slot_size
46    }
47
48    pub const fn slots_for(
49        self,
50        payload_len: usize
51    ) -> usize {
52        payload_len.div_ceil(self.slot_size)
53    }
54
55    /// Physical chunk geometry for this arena. Runtime policy chooses the
56    /// slot count independently for each request or response.
57    pub const fn chunk_geometry(self) -> Option<ChunkGeometry> {
58        ChunkGeometry::new(self.slot_size, self.slots_per_node)
59    }
60
61    /// Plan a known payload with the benchmark-backed default chunk target,
62    /// clamped so one chunk always fits in this node lane.
63    pub const fn plan_chunks(
64        self,
65        data_bytes: usize
66    ) -> Option<ChunkPlan> {
67        let lane_bytes = self.lane_bytes();
68        let limit = if DEFAULT_CHUNK_BYTES < lane_bytes { DEFAULT_CHUNK_BYTES } else { lane_bytes };
69        ChunkPlan::for_limit(data_bytes, self.slot_size, limit)
70    }
71
72    /// Plan using a runtime-selected number of slots per publication.
73    pub const fn plan_chunks_with(
74        self,
75        data_bytes: usize,
76        slots_per_chunk: usize
77    ) -> Option<ChunkPlan> {
78        let geometry = match self.chunk_geometry() {
79            Some(geometry) => geometry,
80            None => return None
81        };
82        geometry.plan(data_bytes, slots_per_chunk)
83    }
84
85    fn validate(self) -> Result<()> {
86        if self.slots_per_node == 0
87            || self.slot_size == 0
88            || !self.slots_per_node.is_power_of_two()
89            || !self.slot_size.is_power_of_two()
90            || self.slots_per_node > u32::MAX as usize
91            || self.slot_size > u32::MAX as usize
92        {
93            return Err(Error::Malformed(format!(
94                "payload arena kind={} slots_per_node={} slot_size={}: both geometry values must be non-zero powers of two fitting u32",
95                self.kind, self.slots_per_node, self.slot_size
96            )));
97        }
98        Ok(())
99    }
100}
101
102#[repr(C, align(64))]
103struct Header {
104    magic: u32,
105    version: u16,
106    header_size: u16,
107    slot_meta_size: u32,
108    slot_size: u32,
109    slots_per_node: u32,
110    fleet_capacity: u16,
111    _reserved: [u8; 2],
112    next_generation: AtomicU64,
113    epoch: AtomicU64,
114    _reserved_credit: [u8; 24]
115}
116
117impl Header {
118    fn new(
119        fleet_capacity: u16,
120        spec: PayloadArenaSpec
121    ) -> Self {
122        Self {
123            magic: MAGIC,
124            version: VERSION,
125            header_size: size_of::<Self>() as u16,
126            slot_meta_size: size_of::<SlotMeta>() as u32,
127            slot_size: spec.slot_size as u32,
128            slots_per_node: spec.slots_per_node as u32,
129            fleet_capacity,
130            _reserved: [0; 2],
131            next_generation: AtomicU64::new(1),
132            epoch: AtomicU64::new(1),
133            _reserved_credit: [0; 24]
134        }
135    }
136
137    fn compatible(
138        &self,
139        fleet_capacity: u16,
140        spec: PayloadArenaSpec
141    ) -> bool {
142        self.magic == MAGIC
143            && self.version == VERSION
144            && self.header_size as usize == size_of::<Self>()
145            && self.slot_meta_size as usize == size_of::<SlotMeta>()
146            && self.slot_size as usize == spec.slot_size
147            && self.slots_per_node as usize == spec.slots_per_node
148            && self.fleet_capacity == fleet_capacity
149    }
150}
151
152#[repr(C, align(64))]
153struct CreditWord {
154    generation: AtomicU32,
155    waiters: AtomicU32,
156    _padding: [u8; 56]
157}
158
159#[repr(C, align(8))]
160struct SlotMeta {
161    state: AtomicU8,
162    _reserved: AtomicU8,
163    reader_node: std::sync::atomic::AtomicU16,
164    allocation_first: AtomicU64,
165    generation: AtomicU64,
166    producer_incarnation: AtomicU64,
167    reader_incarnation: AtomicU64
168}
169
170const _: () = assert!(size_of::<Header>() == 64);
171const _: () = assert!(size_of::<CreditWord>() == 64);
172const _: () = assert!(size_of::<SlotMeta>() == 40);
173
174#[derive(Clone, Copy)]
175struct Geometry {
176    slots_per_node: usize,
177    slot_size: usize,
178    total_slots: usize,
179    credits_offset: usize,
180    metadata_offset: usize,
181    payload_offset: usize,
182    segment_size: usize
183}
184
185impl Geometry {
186    fn new(
187        fleet_capacity: u16,
188        spec: PayloadArenaSpec
189    ) -> Self {
190        let total_slots = usize::from(fleet_capacity) * spec.slots_per_node;
191        let credits_offset = size_of::<Header>();
192        let metadata_offset =
193            credits_offset + usize::from(fleet_capacity) * size_of::<CreditWord>();
194        let payload_offset =
195            (metadata_offset + total_slots * size_of::<SlotMeta>()).next_multiple_of(64);
196        let segment_size = payload_offset + total_slots * spec.slot_size;
197        Self {
198            slots_per_node: spec.slots_per_node,
199            slot_size: spec.slot_size,
200            total_slots,
201            credits_offset,
202            metadata_offset,
203            payload_offset,
204            segment_size
205        }
206    }
207}
208
209enum Backing {
210    Memory(AlignedBytes),
211    #[cfg(unix)]
212    Shm(ShmRegion)
213}
214
215struct AlignedBytes {
216    ptr: *mut u8,
217    layout: std::alloc::Layout
218}
219
220impl AlignedBytes {
221    fn zeroed(size: usize) -> Self {
222        let layout = std::alloc::Layout::from_size_align(size, 64).expect("payload arena layout");
223        // SAFETY: geometry always includes the non-empty header.
224        let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
225        assert!(!ptr.is_null(), "payload arena allocation failed");
226        Self { ptr, layout }
227    }
228}
229
230impl Drop for AlignedBytes {
231    fn drop(&mut self) {
232        // SAFETY: allocated by `alloc_zeroed` with this exact layout.
233        unsafe { std::alloc::dealloc(self.ptr, self.layout) }
234    }
235}
236
237// SAFETY: mapped bytes are accessed through atomics and allocation ownership.
238unsafe impl Send for AlignedBytes {}
239unsafe impl Sync for AlignedBytes {}
240
241struct Arena {
242    _fleet: Arc<Fleet>,
243    backing: Backing,
244    geometry: Geometry,
245    kind: u8,
246    node: u16,
247    incarnation: Incarnation,
248    allocation: Mutex<usize>,
249    credit_wakers: Mutex<Vec<Waker>>,
250    driver: Mutex<Option<Driver>>
251}
252
253impl Arena {
254    fn base(&self) -> *mut u8 {
255        match &self.backing {
256            Backing::Memory(bytes) => bytes.ptr,
257            #[cfg(unix)]
258            Backing::Shm(region) => region.as_ptr()
259        }
260    }
261
262    fn header(&self) -> &Header {
263        // SAFETY: every backing begins with the initialized arena header.
264        unsafe { &*self.base().cast::<Header>() }
265    }
266
267    fn metadata(&self) -> &[SlotMeta] {
268        // SAFETY: geometry reserves this aligned range for atomic metadata.
269        unsafe {
270            std::slice::from_raw_parts(
271                self.base().add(self.geometry.metadata_offset).cast::<SlotMeta>(),
272                self.geometry.total_slots
273            )
274        }
275    }
276
277    fn credits(&self) -> &[CreditWord] {
278        // SAFETY: geometry reserves one cache-line-aligned word per fleet node.
279        unsafe {
280            std::slice::from_raw_parts(
281                self.base().add(self.geometry.credits_offset).cast::<CreditWord>(),
282                self.geometry.total_slots / self.geometry.slots_per_node
283            )
284        }
285    }
286
287    fn local_credit(&self) -> &CreditWord {
288        &self.credits()[usize::from(self.node)]
289    }
290
291    fn payload(
292        &self,
293        absolute_slot: usize
294    ) -> *mut u8 {
295        // SAFETY: callers validate the slot against `total_slots`.
296        unsafe {
297            self.base().add(self.geometry.payload_offset + absolute_slot * self.geometry.slot_size)
298        }
299    }
300
301    fn reserve(
302        self: &Arc<Self>,
303        payload_len: usize
304    ) -> Result<Publication> {
305        let count = self.required_slots(payload_len)?;
306
307        let mut hint = lock_unpoisoned(&self.allocation);
308        let lane_start = usize::from(self.node) * self.geometry.slots_per_node;
309        let candidate = (0..self.geometry.slots_per_node)
310            .map(|offset| (*hint + offset) & (self.geometry.slots_per_node - 1))
311            .find(|&local| {
312                local + count <= self.geometry.slots_per_node
313                    && self.metadata()[lane_start + local..lane_start + local + count]
314                        .iter()
315                        .all(|slot| slot.state.load(Ordering::Acquire) == SLOT_FREE)
316            })
317            .ok_or(Error::PayloadFull { requested_slots: count })?;
318        let first = lane_start + candidate;
319        for slot in &self.metadata()[first..first + count] {
320            slot.state.store(SLOT_RESERVED, Ordering::Relaxed);
321        }
322        let mut generation = self.header().next_generation.fetch_add(1, Ordering::Relaxed);
323        if generation == 0 {
324            generation = self.header().next_generation.fetch_add(1, Ordering::Relaxed);
325        }
326        for slot in &self.metadata()[first..first + count] {
327            slot.allocation_first.store(first as u64, Ordering::Relaxed);
328            slot.generation.store(generation, Ordering::Relaxed);
329            slot.producer_incarnation.store(self.incarnation.get(), Ordering::Relaxed);
330            slot.reader_node.store(u16::MAX, Ordering::Relaxed);
331            slot.reader_incarnation.store(0, Ordering::Relaxed);
332        }
333        self.metadata()[first].state.store(SLOT_RESERVED, Ordering::Release);
334        *hint = (candidate + count) & (self.geometry.slots_per_node - 1);
335        Ok(Publication {
336            arena: Arc::clone(self),
337            first,
338            count,
339            payload_len,
340            generation,
341            published: false
342        })
343    }
344
345    fn release(
346        &self,
347        first: usize,
348        count: usize,
349        generation: u64
350    ) {
351        let slots = &self.metadata()[first..first + count];
352        if slots.iter().any(|slot| slot.generation.load(Ordering::Acquire) != generation) {
353            return;
354        }
355        for slot in slots.iter().skip(1) {
356            slot.state.store(SLOT_FREE, Ordering::Relaxed);
357        }
358        slots[0].state.store(SLOT_FREE, Ordering::Release);
359        let owner = first / self.geometry.slots_per_node;
360        let credit = &self.credits()[owner];
361        credit.generation.fetch_add(1, Ordering::SeqCst);
362        if credit.waiters.load(Ordering::SeqCst) > 0 {
363            crate::wake_on(&credit.generation);
364        }
365    }
366
367    fn required_slots(
368        &self,
369        payload_len: usize
370    ) -> Result<usize> {
371        if payload_len == 0 {
372            return Err(Error::Malformed("an empty payload needs no arena allocation".to_owned()));
373        }
374        let count = payload_len.div_ceil(self.geometry.slot_size);
375        if count > self.geometry.slots_per_node {
376            return Err(Error::PayloadTooLarge {
377                len: payload_len,
378                capacity: self.geometry.slots_per_node * self.geometry.slot_size
379            });
380        }
381        Ok(count)
382    }
383
384    fn has_run(
385        &self,
386        count: usize
387    ) -> bool {
388        let lane_start = usize::from(self.node) * self.geometry.slots_per_node;
389        (0..=self.geometry.slots_per_node - count).any(|local| {
390            self.metadata()[lane_start + local..lane_start + local + count]
391                .iter()
392                .all(|slot| slot.state.load(Ordering::Acquire) == SLOT_FREE)
393        })
394    }
395
396    fn wait_available(
397        &self,
398        count: usize
399    ) -> Result<()> {
400        let credit = self.local_credit();
401        loop {
402            if self.has_run(count) {
403                return Ok(());
404            }
405            credit.waiters.fetch_add(1, Ordering::SeqCst);
406            let seen = credit.generation.load(Ordering::SeqCst);
407            let outcome =
408                if self.has_run(count) { Ok(()) } else { crate::wait_on(&credit.generation, seen) };
409            credit.waiters.fetch_sub(1, Ordering::SeqCst);
410            outcome?;
411        }
412    }
413
414    fn poll_available(
415        self: &Arc<Self>,
416        count: usize,
417        cx: &mut Context<'_>
418    ) -> Poll<Result<()>> {
419        if self.has_run(count) {
420            return Poll::Ready(Ok(()));
421        }
422        {
423            let mut wakers = lock_unpoisoned(&self.credit_wakers);
424            if !wakers.iter().any(|waker| waker.will_wake(cx.waker())) {
425                wakers.push(cx.waker().clone());
426            }
427        }
428        if let Err(error) = self.ensure_driver() {
429            return Poll::Ready(Err(error));
430        }
431        if self.has_run(count) { Poll::Ready(Ok(())) } else { Poll::Pending }
432    }
433
434    fn ensure_driver(self: &Arc<Self>) -> Result<()> {
435        let mut driver = lock_unpoisoned(&self.driver);
436        if driver.is_none() {
437            *driver = Some(Driver::start(
438                Arc::as_ptr(self),
439                format!("orbit-payload-{}-{}-driver", self.kind, self.node)
440            )?);
441        }
442        Ok(())
443    }
444
445    fn extent_count(
446        &self,
447        first: usize,
448        generation: u64
449    ) -> usize {
450        let lane_end = (first / self.geometry.slots_per_node + 1) * self.geometry.slots_per_node;
451        self.metadata()[first..lane_end]
452            .iter()
453            .take_while(|slot| {
454                slot.allocation_first.load(Ordering::Acquire) as usize == first
455                    && slot.generation.load(Ordering::Acquire) == generation
456            })
457            .count()
458    }
459
460    fn node_dead(
461        &self,
462        node: u16,
463        incarnation: Incarnation
464    ) {
465        let metadata = self.metadata();
466        for (first, slot) in metadata.iter().enumerate() {
467            let state = slot.state.load(Ordering::Acquire);
468            let producer_node = first / self.geometry.slots_per_node;
469            let allocation_start = slot.allocation_first.load(Ordering::Acquire) as usize == first;
470            let abandoned_publication = allocation_start
471                && matches!(state, SLOT_RESERVED | SLOT_LIVE)
472                && producer_node == usize::from(node)
473                && slot.producer_incarnation.load(Ordering::Acquire) == incarnation.get();
474            let abandoned_read = state == SLOT_READING
475                && slot.reader_node.load(Ordering::Acquire) == node
476                && slot.reader_incarnation.load(Ordering::Acquire) == incarnation.get();
477            if !abandoned_publication && !abandoned_read {
478                continue;
479            }
480            if slot
481                .state
482                .compare_exchange(state, SLOT_RECLAIMING, Ordering::SeqCst, Ordering::Acquire)
483                .is_err()
484            {
485                continue;
486            }
487            let generation = slot.generation.load(Ordering::Acquire);
488            let count = self.extent_count(first, generation);
489            if count != 0 {
490                self.release(first, count, generation);
491            }
492        }
493    }
494}
495
496impl Doorstep for Arena {
497    fn generation(&self) -> &AtomicU32 {
498        &self.local_credit().generation
499    }
500
501    fn listening(
502        &self,
503        delta: i32
504    ) {
505        if delta > 0 {
506            self.local_credit().waiters.fetch_add(1, Ordering::SeqCst);
507        } else {
508            self.local_credit().waiters.fetch_sub(1, Ordering::SeqCst);
509        }
510    }
511
512    fn drain(&self) {
513        let wakers = std::mem::take(&mut *lock_unpoisoned(&self.credit_wakers));
514        for waker in wakers {
515            waker.wake();
516        }
517    }
518}
519
520impl Drop for Arena {
521    fn drop(&mut self) {
522        if let Some(mut driver) = lock_unpoisoned(&self.driver).take() {
523            driver.stop(&self.local_credit().generation);
524        }
525    }
526}
527
528/// One fleet-wide payload allocation table. Every producer allocates from its
529/// node's exclusive lane, independent of which exchange side it currently holds.
530#[derive(Clone)]
531pub struct PayloadArena {
532    arena: Arc<Arena>
533}
534
535impl PayloadArena {
536    pub fn open(
537        fleet: Arc<Fleet>,
538        incarnation: Incarnation,
539        spec: PayloadArenaSpec
540    ) -> Result<Self> {
541        spec.validate()?;
542        Ok(Self { arena: open(&fleet, incarnation, spec)? })
543    }
544
545    pub fn kind(&self) -> u8 {
546        self.arena.kind
547    }
548
549    pub fn slot_size(&self) -> usize {
550        self.arena.geometry.slot_size
551    }
552
553    pub fn slots_per_node(&self) -> usize {
554        self.arena.geometry.slots_per_node
555    }
556
557    pub fn chunk_geometry(&self) -> ChunkGeometry {
558        // PayloadArena::open validates both geometry values as non-zero.
559        ChunkGeometry::new(self.slot_size(), self.slots_per_node())
560            .expect("opened payload arena has valid chunk geometry")
561    }
562
563    pub fn plan_chunks(
564        &self,
565        data_bytes: usize
566    ) -> Result<ChunkPlan> {
567        PayloadArenaSpec::new(self.kind(), self.slots_per_node(), self.slot_size())
568            .plan_chunks(data_bytes)
569            .ok_or_else(|| {
570                Error::Malformed("payload arena cannot plan zero-sized geometry".to_owned())
571            })
572    }
573
574    pub fn plan_chunks_with(
575        &self,
576        data_bytes: usize,
577        slots_per_chunk: usize
578    ) -> Result<ChunkPlan> {
579        self.chunk_geometry().plan(data_bytes, slots_per_chunk).ok_or_else(|| {
580            Error::Malformed(format!(
581                "chunk slot count {slots_per_chunk} exceeds payload lane capacity {}",
582                self.slots_per_node()
583            ))
584        })
585    }
586    /// Park this thread until a run large enough for `payload_len` may be
587    /// available. Allocation still decides the race after the wake.
588    pub fn wait_available(
589        &self,
590        payload_len: usize
591    ) -> Result<()> {
592        let count = self.arena.required_slots(payload_len)?;
593        self.arena.wait_available(count)
594    }
595
596    /// Whether this producer lane currently has a contiguous run for the
597    /// payload. This is only a readiness snapshot; allocation still decides
598    /// a race between concurrent producers.
599    pub fn is_available(
600        &self,
601        payload_len: usize
602    ) -> Result<bool> {
603        let count = self.arena.required_slots(payload_len)?;
604        Ok(self.arena.has_run(count))
605    }
606
607    /// Task readiness for this node's payload credit. Credit returns are
608    /// coalesced through one shared generation and one local driver.
609    pub fn poll_available(
610        &self,
611        payload_len: usize,
612        cx: &mut Context<'_>
613    ) -> Poll<Result<()>> {
614        let count = match self.arena.required_slots(payload_len) {
615            Ok(count) => count,
616            Err(error) => return Poll::Ready(Err(error))
617        };
618        self.arena.poll_available(count, cx)
619    }
620
621    /// Clear this arena only while the fleet is known quiescent. Normal
622    /// attach and replacement never call this implicitly.
623    pub fn reset_all(&self) {
624        let mut hint = lock_unpoisoned(&self.arena.allocation);
625        *hint = 0;
626        for slot in self.arena.metadata() {
627            slot.state.store(SLOT_FREE, Ordering::Release);
628        }
629        for credit in self.arena.credits() {
630            credit.generation.fetch_add(1, Ordering::SeqCst);
631            crate::wake_on(&credit.generation);
632        }
633    }
634
635    /// Reclaim only allocations owned by a process incarnation whose death
636    /// was confirmed by the embedder. A producer's unpublished or unread
637    /// chunks and a dead reader's held chunks return; a chunk already held by
638    /// a surviving consumer remains that consumer's.
639    pub fn node_dead(
640        &self,
641        node: orbit_core::NodeId,
642        incarnation: Incarnation
643    ) {
644        self.arena.node_dead(node.get(), incarnation);
645    }
646
647    /// Remove the arena's SHM name. Existing mappings remain valid.
648    #[cfg(unix)]
649    pub fn unlink(&self) -> Result<()> {
650        match &self.arena.backing {
651            Backing::Memory(_) => {
652                self.reset_all();
653                Ok(())
654            }
655            Backing::Shm(region) => region.unlink().map_err(Error::Io)
656        }
657    }
658
659    #[cfg(test)]
660    pub(crate) fn publish(
661        &self,
662        payload: &[u8]
663    ) -> Result<Publication> {
664        let mut publication = self.reserve(payload.len())?;
665        publication.as_mut_slice().copy_from_slice(payload);
666        publication.make_live();
667        Ok(publication)
668    }
669
670    pub(crate) fn reserve(
671        &self,
672        payload_len: usize
673    ) -> Result<Publication> {
674        self.arena.reserve(payload_len)
675    }
676
677    pub(crate) fn read(
678        &self,
679        descriptor: ChunkDescriptor
680    ) -> Result<PayloadChunk> {
681        if descriptor.arena_kind() != self.kind() {
682            return Err(Error::Malformed(format!(
683                "chunk names payload arena kind {}, opened kind is {}",
684                descriptor.arena_kind(),
685                self.kind()
686            )));
687        }
688        let owner = usize::from(descriptor.owner_node());
689        let first_local = descriptor.first_slot() as usize;
690        let count = descriptor.slot_count() as usize;
691        let len = descriptor.payload_len() as usize;
692        if owner >= self.arena.geometry.total_slots / self.arena.geometry.slots_per_node
693            || count == 0
694            || first_local + count > self.arena.geometry.slots_per_node
695            || len == 0
696            || len > count * self.arena.geometry.slot_size
697            || (count > 1 && len <= (count - 1) * self.arena.geometry.slot_size)
698        {
699            return Err(Error::Malformed(
700                "chunk descriptor is outside its payload lane".to_owned()
701            ));
702        }
703        let first = owner * self.arena.geometry.slots_per_node + first_local;
704        let slots = &self.arena.metadata()[first..first + count];
705        let generation = descriptor.allocation_generation();
706        if slots.iter().any(|slot| slot.generation.load(Ordering::Acquire) != generation)
707            || slots.iter().skip(1).any(|slot| slot.state.load(Ordering::Acquire) != SLOT_RESERVED)
708            || slots[0]
709                .state
710                .compare_exchange(SLOT_LIVE, SLOT_READING, Ordering::Acquire, Ordering::Acquire)
711                .is_err()
712        {
713            return Err(Error::Malformed(
714                "chunk allocation is stale or already consumed".to_owned()
715            ));
716        }
717        slots[0].reader_incarnation.store(self.arena.incarnation.get(), Ordering::Release);
718        slots[0].reader_node.store(self.arena.node, Ordering::Release);
719        Ok(PayloadChunk {
720            arena: Arc::clone(&self.arena),
721            first,
722            count,
723            len,
724            generation,
725            descriptor
726        })
727    }
728}
729
730pub(crate) struct Publication {
731    arena: Arc<Arena>,
732    first: usize,
733    count: usize,
734    payload_len: usize,
735    generation: u64,
736    published: bool
737}
738
739impl Publication {
740    pub(crate) fn as_slice(&self) -> &[u8] {
741        // SAFETY: this publication owns a contiguous reserved extent and no
742        // consumer can observe it before the control descriptor is sent.
743        unsafe { std::slice::from_raw_parts(self.arena.payload(self.first), self.payload_len) }
744    }
745
746    pub(crate) fn as_mut_slice(&mut self) -> &mut [u8] {
747        // SAFETY: this publication exclusively owns a contiguous reserved
748        // extent until it is made live and its control descriptor is sent.
749        unsafe { std::slice::from_raw_parts_mut(self.arena.payload(self.first), self.payload_len) }
750    }
751
752    pub(crate) fn coordinates(&self) -> (u64, u32, u32, u32, u8, u16) {
753        let first_local = self.first % self.arena.geometry.slots_per_node;
754        (
755            self.generation,
756            first_local as u32,
757            self.count as u32,
758            self.payload_len as u32,
759            self.arena.kind,
760            self.arena.node
761        )
762    }
763
764    pub(crate) fn truncate(
765        &mut self,
766        payload_len: usize
767    ) -> Result<()> {
768        if payload_len == 0 || payload_len > self.payload_len {
769            return Err(Error::Malformed(format!(
770                "committed payload length {payload_len} is outside reserved capacity {}",
771                self.payload_len
772            )));
773        }
774        let count = self.arena.required_slots(payload_len)?;
775        if count < self.count {
776            for slot in &self.arena.metadata()[self.first + count..self.first + self.count] {
777                slot.state.store(SLOT_FREE, Ordering::Release);
778            }
779            self.count = count;
780            let credit = self.arena.local_credit();
781            credit.generation.fetch_add(1, Ordering::SeqCst);
782            if credit.waiters.load(Ordering::SeqCst) > 0 {
783                crate::wake_on(&credit.generation);
784            }
785        }
786        self.payload_len = payload_len;
787        Ok(())
788    }
789
790    pub(crate) fn make_live(&self) {
791        self.arena.metadata()[self.first].state.store(SLOT_LIVE, Ordering::Release);
792    }
793
794    pub(crate) fn mark_published(mut self) {
795        self.published = true;
796    }
797}
798
799impl Drop for Publication {
800    fn drop(&mut self) {
801        if !self.published {
802            self.arena.release(self.first, self.count, self.generation);
803        }
804    }
805}
806
807/// An immutable chunk borrowed from a payload arena. Dropping the guard is
808/// the consumer's credit return to its producer node's lane.
809pub struct PayloadChunk {
810    arena: Arc<Arena>,
811    first: usize,
812    count: usize,
813    len: usize,
814    generation: u64,
815    descriptor: ChunkDescriptor
816}
817
818impl PayloadChunk {
819    pub const fn descriptor(&self) -> ChunkDescriptor {
820        self.descriptor
821    }
822
823    pub fn as_slice(&self) -> &[u8] {
824        // SAFETY: the allocation is immutable between publication and this
825        // guard's release, and `len` was validated against the run.
826        unsafe { std::slice::from_raw_parts(self.arena.payload(self.first), self.len) }
827    }
828}
829
830impl Deref for PayloadChunk {
831    type Target = [u8];
832
833    fn deref(&self) -> &Self::Target {
834        self.as_slice()
835    }
836}
837
838impl Drop for PayloadChunk {
839    fn drop(&mut self) {
840        self.arena.release(self.first, self.count, self.generation);
841    }
842}
843
844#[derive(Hash, Eq, PartialEq)]
845enum Key {
846    Memory(usize, u8),
847    #[cfg(unix)]
848    Shm(String, u16)
849}
850
851static ARENAS: LazyLock<Mutex<HashMap<Key, Weak<Arena>>>> =
852    LazyLock::new(|| Mutex::new(HashMap::new()));
853
854fn open(
855    fleet: &Arc<Fleet>,
856    incarnation: Incarnation,
857    spec: PayloadArenaSpec
858) -> Result<Arc<Arena>> {
859    if !crate::waits_supported() {
860        return Err(Error::Io(std::io::Error::new(
861            std::io::ErrorKind::Unsupported,
862            "payload arenas need a platform that can wait on a shared word"
863        )));
864    }
865    let key = if fleet.is_shm() {
866        #[cfg(unix)]
867        {
868            Key::Shm(ring_segment_name(fleet.name(), spec.kind), fleet.node_id().get())
869        }
870        #[cfg(not(unix))]
871        unreachable!("non-Unix fleets cannot use POSIX SHM")
872    } else {
873        Key::Memory(Arc::as_ptr(fleet) as usize, spec.kind)
874    };
875    let mut arenas = lock_unpoisoned(&ARENAS);
876    arenas.retain(|_, arena| arena.strong_count() > 0);
877    if let Some(arena) = arenas.get(&key).and_then(Weak::upgrade) {
878        if arena.incarnation != incarnation {
879            return Err(Error::Malformed(format!(
880                "this process already opened payload kind {} as incarnation {}",
881                spec.kind,
882                arena.incarnation.get()
883            )));
884        }
885        if arena.geometry.slots_per_node != spec.slots_per_node
886            || arena.geometry.slot_size != spec.slot_size
887        {
888            return Err(Error::Malformed(format!(
889                "this process already opened payload kind {} with slots_per_node={} slot_size={}",
890                spec.kind, arena.geometry.slots_per_node, arena.geometry.slot_size
891            )));
892        }
893        return Ok(arena);
894    }
895
896    let geometry = Geometry::new(fleet.fleet_capacity(), spec);
897    let backing = match &key {
898        Key::Memory(..) => {
899            let bytes = AlignedBytes::zeroed(geometry.segment_size);
900            // SAFETY: fresh aligned memory is at least one header long.
901            unsafe {
902                std::ptr::write(
903                    bytes.ptr.cast::<Header>(),
904                    Header::new(fleet.fleet_capacity(), spec)
905                );
906            }
907            Backing::Memory(bytes)
908        }
909        #[cfg(unix)]
910        Key::Shm(name, _) => Backing::Shm(open_shm(name, fleet.fleet_capacity(), spec, geometry)?)
911    };
912    let arena = Arc::new(Arena {
913        _fleet: Arc::clone(fleet),
914        backing,
915        geometry,
916        kind: spec.kind,
917        node: fleet.node_id().get(),
918        incarnation,
919        allocation: Mutex::new(0),
920        credit_wakers: Mutex::new(Vec::new()),
921        driver: Mutex::new(None)
922    });
923    arenas.insert(key, Arc::downgrade(&arena));
924    Ok(arena)
925}
926
927#[cfg(unix)]
928fn open_shm(
929    name: &str,
930    fleet_capacity: u16,
931    spec: PayloadArenaSpec,
932    geometry: Geometry
933) -> Result<ShmRegion> {
934    use std::io;
935
936    let (region, _initialization_lock) =
937        ShmRegion::open_or_create_locked(name, geometry.segment_size)?;
938    if region.created() {
939        // SAFETY: a fresh mapping is aligned and at least one header long.
940        unsafe {
941            std::ptr::write(region.as_ptr().cast::<Header>(), Header::new(fleet_capacity, spec));
942        }
943    } else {
944        // SAFETY: the open verified the minimum segment size.
945        let header = unsafe { &*region.as_ptr().cast::<Header>() };
946        if header.magic != MAGIC {
947            return Err(Error::Io(io::Error::new(
948                io::ErrorKind::InvalidData,
949                format!("SHM segment {name} has the wrong payload-arena magic")
950            )));
951        }
952        if !header.compatible(fleet_capacity, spec) {
953            return Err(Error::Io(io::Error::new(
954                io::ErrorKind::InvalidData,
955                format!("SHM segment {name} has an incompatible payload-arena layout")
956            )));
957        }
958    }
959    Ok(region)
960}
961
962pub fn segment_size_for(
963    fleet_capacity: u16,
964    spec: PayloadArenaSpec
965) -> usize {
966    Geometry::new(fleet_capacity, spec).segment_size
967}
968
969#[cfg(test)]
970mod tests {
971    use super::*;
972    use crate::exchange::{ExchangeId, Flow};
973
974    fn fleet() -> Arc<Fleet> {
975        Arc::new(Fleet::join("payload-arena-test", 2).expect("fleet"))
976    }
977
978    fn descriptor(
979        publication: &Publication,
980        chunk_id: u64
981    ) -> ChunkDescriptor {
982        let (generation, first, count, len, kind, owner) = publication.coordinates();
983        ChunkDescriptor::new(
984            ExchangeId::from_stream_id(crate::StreamId::from_net_id(orbit_core::NetId64::make(
985                240, 0, 1
986            ))),
987            Flow::AtoB,
988            chunk_id,
989            generation,
990            first,
991            count,
992            len,
993            kind,
994            owner
995        )
996    }
997
998    #[test]
999    fn one_chunk_spans_the_number_of_slots_its_payload_needs() {
1000        let arena =
1001            PayloadArena::open(fleet(), Incarnation::new(1), PayloadArenaSpec::new(241, 8, 256))
1002                .expect("arena");
1003        let bytes = vec![0x5a; 777];
1004        let publication = arena.publish(&bytes).expect("publication");
1005        let descriptor = descriptor(&publication, 1);
1006        assert_eq!(descriptor.slot_count(), 4);
1007        publication.mark_published();
1008
1009        let chunk = arena.read(descriptor).expect("chunk");
1010        assert_eq!(&*chunk, bytes);
1011    }
1012
1013    #[test]
1014    fn dropping_a_chunk_returns_the_whole_extent_as_credit() {
1015        let arena =
1016            PayloadArena::open(fleet(), Incarnation::new(1), PayloadArenaSpec::new(242, 4, 64))
1017                .expect("arena");
1018        let first = arena.publish(&[1; 256]).expect("fills lane");
1019        let descriptor = descriptor(&first, 1);
1020        first.mark_published();
1021        assert!(matches!(arena.publish(&[2]), Err(Error::PayloadFull { .. })));
1022        drop(arena.read(descriptor).expect("consume"));
1023        assert!(arena.publish(&[3]).is_ok());
1024    }
1025
1026    #[test]
1027    fn a_cancelled_publication_never_spends_credit() {
1028        let arena =
1029            PayloadArena::open(fleet(), Incarnation::new(1), PayloadArenaSpec::new(243, 2, 64))
1030                .expect("arena");
1031        drop(arena.publish(&[1; 128]).expect("reserved publication"));
1032        assert!(arena.publish(&[2; 128]).is_ok());
1033    }
1034
1035    #[test]
1036    fn returned_credit_wakes_a_parked_producer() {
1037        let arena =
1038            PayloadArena::open(fleet(), Incarnation::new(1), PayloadArenaSpec::new(244, 2, 64))
1039                .expect("arena");
1040        let publication = arena.publish(&[1; 128]).expect("fills lane");
1041        let descriptor = descriptor(&publication, 1);
1042        publication.mark_published();
1043        let chunk = arena.read(descriptor).expect("held chunk");
1044
1045        let waiting = arena.clone();
1046        let waiter = std::thread::spawn(move || waiting.wait_available(1));
1047        std::thread::sleep(std::time::Duration::from_millis(20));
1048        drop(chunk);
1049        waiter.join().expect("waiter").expect("credit wake");
1050    }
1051
1052    #[cfg(unix)]
1053    #[test]
1054    fn returned_credit_wakes_only_the_owning_producer_node() {
1055        let name: &'static str = Box::leak(format!("pc{:x}", std::process::id()).into_boxed_str());
1056        let spec = PayloadArenaSpec::new(248, 1, 64);
1057        let producer = PayloadArena::open(
1058            Arc::new(
1059                Fleet::join_shm_as(name, 2, orbit_core::NodeId::ZERO).expect("producer fleet")
1060            ),
1061            Incarnation::new(1),
1062            spec
1063        )
1064        .expect("producer arena");
1065        producer.reset_all();
1066        let consumer = PayloadArena::open(
1067            Arc::new(
1068                Fleet::join_shm_as(name, 2, orbit_core::NodeId::new(1)).expect("consumer fleet")
1069            ),
1070            Incarnation::new(2),
1071            spec
1072        )
1073        .expect("consumer arena");
1074
1075        let publication = producer.publish(&[7; 64]).expect("fill producer lane");
1076        let descriptor = descriptor(&publication, 1);
1077        publication.mark_published();
1078        let chunk = consumer.read(descriptor).expect("consume producer chunk");
1079
1080        let waiting = producer.clone();
1081        let waiter = std::thread::spawn(move || waiting.wait_available(64));
1082        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
1083        while producer.arena.local_credit().waiters.load(Ordering::SeqCst) == 0 {
1084            assert!(std::time::Instant::now() < deadline, "producer did not park");
1085            std::thread::yield_now();
1086        }
1087        assert_eq!(
1088            consumer.arena.local_credit().waiters.load(Ordering::SeqCst),
1089            0,
1090            "an unrelated node must not share the producer's credit wait word",
1091        );
1092
1093        drop(chunk);
1094        waiter.join().expect("waiter thread").expect("producer wake");
1095        producer.unlink().expect("unlink payload arena");
1096    }
1097
1098    #[cfg(feature = "tokio")]
1099    #[tokio::test]
1100    async fn returned_credit_wakes_a_pending_task() {
1101        use std::future::poll_fn;
1102
1103        let arena =
1104            PayloadArena::open(fleet(), Incarnation::new(1), PayloadArenaSpec::new(247, 2, 64))
1105                .expect("arena");
1106        let publication = arena.publish(&[1; 128]).expect("fills lane");
1107        let descriptor = descriptor(&publication, 1);
1108        publication.mark_published();
1109        let chunk = arena.read(descriptor).expect("held chunk");
1110
1111        let waiting = arena.clone();
1112        let waiter = tokio::spawn(async move { poll_fn(|cx| waiting.poll_available(1, cx)).await });
1113        tokio::task::yield_now().await;
1114        drop(chunk);
1115        tokio::time::timeout(std::time::Duration::from_secs(2), waiter)
1116            .await
1117            .expect("credit task stayed pending")
1118            .expect("credit task")
1119            .expect("credit wake");
1120    }
1121
1122    #[test]
1123    fn death_reclaims_only_unpublished_or_held_allocations() {
1124        let arena =
1125            PayloadArena::open(fleet(), Incarnation::new(7), PayloadArenaSpec::new(245, 2, 64))
1126                .expect("arena");
1127
1128        let abandoned = arena.arena.reserve(128).expect("reserved by producer");
1129        arena.node_dead(orbit_core::NodeId::ZERO, Incarnation::new(7));
1130        let replacement = arena.publish(&[2; 128]).expect("producer credit reclaimed");
1131        drop(abandoned);
1132        let replacement_descriptor = descriptor(&replacement, 2);
1133        replacement.mark_published();
1134        let held = arena.read(replacement_descriptor).expect("held by reader");
1135
1136        arena.node_dead(orbit_core::NodeId::ZERO, Incarnation::new(6));
1137        assert!(matches!(arena.publish(&[3]), Err(Error::PayloadFull { .. })));
1138        arena.node_dead(orbit_core::NodeId::ZERO, Incarnation::new(7));
1139        let after_reader_death = arena.publish(&[4; 128]).expect("reader credit reclaimed");
1140        drop(held);
1141        let after_descriptor = descriptor(&after_reader_death, 3);
1142        after_reader_death.mark_published();
1143        assert!(arena.read(after_descriptor).is_ok());
1144    }
1145
1146    #[test]
1147    fn committed_unread_payload_is_reclaimed_with_its_dead_producer() {
1148        let arena =
1149            PayloadArena::open(fleet(), Incarnation::new(8), PayloadArenaSpec::new(246, 2, 64))
1150                .expect("arena");
1151        let publication = arena.publish(b"survives").expect("publication");
1152        let descriptor = descriptor(&publication, 1);
1153        publication.mark_published();
1154
1155        arena.node_dead(orbit_core::NodeId::ZERO, Incarnation::new(8));
1156        assert!(arena.read(descriptor).is_err());
1157        assert!(arena.publish(&[9; 128]).is_ok());
1158    }
1159}