Skip to main content

dope_core/driver/retained/accept/
mod.rs

1use std::{cell, mem, net, ops::ControlFlow, pin};
2
3use dope_sys::io::socket::addr::{Length, Storage};
4
5use crate::{
6    driver,
7    driver::{
8        life::finish,
9        result,
10        retained::{accept, arm, flight},
11        route,
12        route::kind,
13    },
14    io::{
15        event::{batch::Flow, net::accept::Failure},
16        fd::domain::retire,
17        socket,
18    },
19};
20
21pub mod raw;
22
23/// Current descriptor-retirement barrier for admitting a new accept.
24#[derive(Debug)]
25pub enum Readiness {
26    Ready,
27    Pending,
28    Inflight,
29}
30
31impl From<driver::Reference<'_>> for Readiness {
32    /// Query again after driver mutations; this snapshot is not an admission permit.
33    fn from(driver: driver::Reference<'_>) -> Self {
34        let retired = driver.descriptors().retirement();
35        if retired.has_pending() {
36            Self::Pending
37        } else if retired.has_inflight() {
38            Self::Inflight
39        } else {
40            Self::Ready
41        }
42    }
43}
44
45impl Readiness {
46    pub fn progress(self) -> ControlFlow<(), bool> {
47        match self {
48            Self::Ready | Self::Pending => ControlFlow::Break(()),
49            Self::Inflight => ControlFlow::Continue(true),
50        }
51    }
52}
53
54#[pin_project::pin_project(!Unpin)]
55pub struct Lane<'d, Tag>
56where
57    Tag: route::Tag<Class = kind::Accept>,
58{
59    state: arm::raw::State<'d, Tag>,
60    addr: cell::UnsafeCell<Storage<Length>>,
61    closed: retire::Completed,
62}
63
64impl<'d, Tag> Lane<'d, Tag>
65where
66    Tag: route::Tag<Class = kind::Accept>,
67{
68    pub fn new(target: route::Target<'d, Tag>) -> Self {
69        Self {
70            state: arm::raw::State::new(target),
71            addr: cell::UnsafeCell::new(Storage::<Length>::empty()),
72            closed: retire::Completed::EMPTY,
73        }
74    }
75}
76
77/// Pinned accept lanes and their exact in-flight count share one owner.
78///
79pub struct Slots<'d, Tag>
80where
81    Tag: route::Tag<Class = kind::Accept>,
82{
83    lanes: pin::Pin<Box<[Lane<'d, Tag>]>>,
84    active: usize,
85}
86
87impl<'d, Tag> Slots<'d, Tag>
88where
89    Tag: route::Tag<Class = kind::Accept>,
90{
91    pub fn new(lanes: Box<[Lane<'d, Tag>]>) -> Self {
92        Self {
93            lanes: Box::into_pin(lanes),
94            active: 0,
95        }
96    }
97
98    pub fn get_mut(&mut self, index: usize) -> Option<Entry<'_, 'd, Tag>> {
99        // SAFETY: the selected lane remains pinned in this owned allocation.
100        let lane = unsafe { self.lanes.as_mut().get_unchecked_mut() }.get_mut(index)?;
101        Some(Entry {
102            lane: unsafe { pin::Pin::new_unchecked(lane) },
103            active: &mut self.active,
104        })
105    }
106
107    fn iter_mut(
108        &mut self,
109    ) -> impl DoubleEndedIterator<Item = pin::Pin<&mut Lane<'d, Tag>>> + ExactSizeIterator + '_
110    {
111        // SAFETY: the boxed slice keeps every lane at a stable address, and
112        // the iterator exposes each exclusive borrow only as pinned.
113        unsafe { self.lanes.as_mut().get_unchecked_mut() }
114            .iter_mut()
115            .map(|lane| unsafe { pin::Pin::new_unchecked(lane) })
116    }
117
118    pub fn len(&self) -> usize {
119        self.lanes.len()
120    }
121
122    /// Returns the number of submitted accepts awaiting terminal retirement.
123    pub const fn active(&self) -> usize {
124        self.active
125    }
126
127    pub fn stop(&mut self, driver: &mut driver::life::Lifecycle<'d, impl crate::io::Report>) {
128        for lane in self.iter_mut() {
129            lane.project().state.stop(driver);
130        }
131    }
132
133    pub fn progress(&self) -> ControlFlow<(), bool> {
134        let mut waiting = false;
135        for lane in self.lanes.iter() {
136            waiting |= lane.state.progress()?;
137        }
138        ControlFlow::Continue(waiting)
139    }
140
141    pub fn finish(&mut self, proof: &mut finish::Finish<'_, 'd, impl crate::io::Report>) {
142        for lane in self.iter_mut() {
143            lane.project().state.finish(proof);
144        }
145        self.active = 0;
146    }
147}
148
149/// An exclusive lane selection retains its owning count through the transition.
150///
151///
152pub struct Entry<'a, 'd, Tag>
153where
154    Tag: route::Tag<Class = kind::Accept>,
155{
156    lane: pin::Pin<&'a mut Lane<'d, Tag>>,
157    active: &'a mut usize,
158}
159
160impl<'a, 'd, Tag> Entry<'a, 'd, Tag>
161where
162    Tag: route::Tag<Class = kind::Accept>,
163{
164    pub fn begin(mut self) -> Option<accept::raw::Arming<'a, 'd, Tag>> {
165        if !self.lane.as_mut().project().state.start() {
166            return None;
167        }
168        Some(accept::raw::Arming::new(self))
169    }
170
171    /// Retires an operation while borrowing its owner's active count.
172    /// The matching lane must have reached native terminal completion.
173    /// Empty owners and pending flights cannot grant terminal access.
174    pub fn retire(mut self, token: route::Erased<'d, kind::Accept>) -> Retire<'a, 'd, Tag> {
175        let lane = self.lane.as_mut().project();
176        let retired = match lane.state.complete(token, Flow::Last) {
177            arm::Disposition::Discard => return Retire::Stale,
178            arm::Disposition::Deliver | arm::Disposition::Probe => {
179                Retired::Terminal(Terminal { lane: self.lane })
180            }
181            arm::Disposition::Retiring => Retired::Cancelled,
182        };
183        // A successful retirement consumes one live lane counted by this owner.
184        *self.active -= 1;
185        Retire::Done(retired)
186    }
187
188    /// Commits a previously idle lane and its owning count together.
189    /// The count cannot exceed the allocated lane slice's length.
190    fn apply(
191        &mut self,
192        result: Result<flight::Flight<'d, kind::Accept>, result::SubmitError>,
193        closed: retire::Completed,
194    ) -> arm::Submission {
195        let lane = self.lane.as_mut().project();
196        let result = lane.state.apply(result);
197        if let arm::Submission::Armed = result {
198            *lane.closed = closed;
199            // Entry owns one distinct idle lane in this count's owned slice.
200            *self.active += 1;
201        }
202        result
203    }
204}
205
206#[must_use]
207pub enum Retire<'a, 'd, Tag>
208where
209    Tag: route::Tag<Class = kind::Accept>,
210{
211    Stale,
212    Done(Retired<'a, 'd, Tag>),
213}
214
215#[must_use]
216pub enum Retired<'a, 'd, Tag>
217where
218    Tag: route::Tag<Class = kind::Accept>,
219{
220    Terminal(Terminal<'a, 'd, Tag>),
221    Cancelled,
222}
223
224#[must_use]
225pub struct Terminal<'a, 'd, Tag>
226where
227    Tag: route::Tag<Class = kind::Accept>,
228{
229    lane: pin::Pin<&'a mut Lane<'d, Tag>>,
230}
231
232impl<'d, Tag> Terminal<'_, 'd, Tag>
233where
234    Tag: route::Tag<Class = kind::Accept>,
235{
236    /// Preserves completed native capacity returns even when their CQE precedes this error.
237    pub fn can_defer(
238        &self,
239        failure: &Failure,
240        driver: &mut driver::life::Lifecycle<'d, impl crate::io::Report>,
241    ) -> bool {
242        failure.can_defer(driver)
243            || (matches!(failure, Failure::Syscall(_))
244                && failure.is_resource()
245                && self.lane.closed != driver.driver_ref().descriptors().retirement().completed())
246    }
247
248    pub fn into_addr(self) -> Result<net::SocketAddr, socket::Error> {
249        let storage = self.lane.project().addr.get_mut();
250        storage.to_std().map_err(socket::Error::from)
251    }
252}
253
254const _: () = {
255    type Tag = route::KeyTag<1, kind::Accept>;
256    const fn layout<'a, 'd: 'a>() {
257        assert!(
258            mem::size_of::<Lane<'d, Tag>>()
259                == mem::size_of::<(arm::raw::State<'d, Tag>, Storage<Length>, retire::Completed)>()
260        );
261        assert!(
262            mem::align_of::<Lane<'d, Tag>>()
263                == mem::align_of::<(arm::raw::State<'d, Tag>, Storage<Length>, retire::Completed)>(
264                )
265        );
266        assert!(
267            mem::size_of::<Slots<'d, Tag>>()
268                == mem::size_of::<(pin::Pin<Box<[Lane<'d, Tag>]>>, usize)>()
269        );
270        assert!(
271            mem::align_of::<Slots<'d, Tag>>() == mem::align_of::<pin::Pin<Box<[Lane<'d, Tag>]>>>()
272        );
273        assert!(mem::size_of::<Terminal<'a, 'd, Tag>>() == mem::size_of::<usize>());
274        assert!(mem::size_of::<Entry<'a, 'd, Tag>>() == 2 * mem::size_of::<usize>());
275        assert!(mem::size_of::<Option<Entry<'a, 'd, Tag>>>() == 2 * mem::size_of::<usize>());
276        assert!(mem::size_of::<accept::raw::Arming<'a, 'd, Tag>>() == 2 * mem::size_of::<usize>());
277    }
278    layout();
279};