use crate::{
Backend,
driver::{
Closing, Key,
engine::envelope::Envelope,
tuning::{self, Progress},
},
reactor::{mappings, register::owned, ring::Ready, sq},
};
use dope_sys::{
Errno,
engine::{
self, Drain, Failure, Mode, Pending as _,
admit::{self, Admit, Context},
register,
ring::{self, Backend as _},
shutdown::{Cause, Shutdown},
},
io::{
Close,
reactor::{
Full, complete,
event::{self, fault},
submit::{self, Control, Poll as _, Queue as _, Ready as _},
},
request,
socket::Create,
},
memory::{
self,
buffer::{self, provided},
},
ring::{
Source,
ready::{self, Complete as _, Ready as _},
},
table::{
self, reclaim,
token::{self, Codec, Tuning, host},
},
};
use o3::{
buffer::storage::provided::native,
mem::{self, slot},
};
use std::{convert::Infallible, mem::MaybeUninit, num, ops::ControlFlow, os::fd, time};
mod drain;
mod envelope;
mod parts;
mod release;
mod retire;
mod socket;
type Identity<C> = <<C as ring::Context>::Token as token::Codec>::Context;
type NativeKey<C> = <Identity<C> as host::Context>::Key;
type NativeControl<C> = <Identity<C> as token::Context>::Control;
type NativeSlot<C> = <Identity<C> as token::Context>::Slot;
type NativeReturned<C> = <Identity<C> as host::Context>::Returned;
type Subject<C, F> = fault::Subject<
<F as host::Flight>::Token,
NativeControl<C>,
fault::Echo<NativeKey<C>>,
NativeSlot<C>,
>;
type Violation<C, F, S, N, H, J> = fault::Violation<
S,
fault::Echo<NativeKey<C>>,
<F as host::Flight>::Length,
N,
crate::error::Returned,
NativeSlot<C>,
<NativeSlot<C> as TryFrom<u32>>::Error,
H,
J,
>;
type NativeFault<C, F, S, N, H, J> =
fault::Fault<<F as host::Flight>::Observation, Subject<C, F>, Violation<C, F, S, N, H, J>>;
type Decoded<T, C, F, S, N, H, J> = Result<Result<T, Errno>, Violation<C, F, S, N, H, J>>;
type NativeReport<F, P, K, M, T, V, X> = event::Reclaimed<
<F as host::Flight>::Fault,
P,
K,
<F as host::Flight>::Token,
T,
<F as host::Flight>::AcceptFailure,
fault::Echo<<F as host::Flight>::Key>,
<F as host::Flight>::Length,
M,
V,
X,
>;
pub struct Engine<C: ring::Context> {
pub(in crate::driver) ring: Ready<C::Token, C::Layout>,
pub(in crate::driver) tuning: C::Tuning,
}
impl<C: ring::Context> engine::Buffer for Engine<C> {
type Layout = C::Layout;
type Token =
<Backend as provided::Source>::Complete<<C::Layout as memory::raw::Receive>::Extent>;
type Context = <Backend as provided::Source>::Context<C::Layout>;
type Retained = ();
type Arena<T> = native::raw::Arena<T>;
type Root<'d, T>
= native::raw::Root<'d, T>
where
T: 'd,
Self::Retained: 'd;
}
impl<C, O, H: fd::AsFd> engine::Install<O, H> for Engine<C>
where
C: ring::Context + Context<Native = Backend>,
O: Into<<C::Inputs as request::Context>::Target>,
{
type Error = <Ready<C::Token, C::Layout> as ready::Ready>::InstallError;
fn install(&mut self, slot: O, handle: H) -> Result<(), Self::Error> {
self.ring.install(
<Backend as request::Source<C::Inputs>>::target(slot.into()),
fd::AsFd::as_fd(&handle),
)
}
}
impl<C: ring::Context> ring::Backend<C> for Engine<C> {
type Ring = Ready<C::Token, C::Layout>;
fn new(ring: Self::Ring, tuning: C::Tuning) -> Self {
Self { ring, tuning }
}
fn ring(&mut self) -> &mut Self::Ring {
&mut self.ring
}
fn tuning(&mut self) -> &mut C::Tuning {
&mut self.tuning
}
fn split(&mut self) -> (&mut Self::Ring, &mut C::Tuning) {
(&mut self.ring, &mut self.tuning)
}
}
impl<C> Admit<C> for Engine<C>
where
C: ring::Context + Context<Native = Backend, Key = Key<C::Token>>,
{
type Admission<'a>
= sq::raw::Vacancy<'a, C::Token>
where
Self: 'a;
fn try_admit(&mut self) -> Result<Self::Admission<'_>, Full> {
self.ring.submission().try_one()
}
}
impl<C> admit::Backend<C> for Engine<C>
where
C: ring::Context + Context<Native = Backend, Key = Key<C::Token>>,
C::Tuning: Progress<C::Token>,
{
fn try_cancel<const FAMILY: u8>(
&mut self,
key: C::Key,
pending: bool,
slot: Option<&<C::Inputs as request::Context>::Target>,
) -> Result<admit::Cancelled, admit::Error<Infallible>> {
if !pending {
return Ok(admit::Cancelled::Completed);
}
let vacant = self
.ring
.submission()
.try_one()
.map_err(admit::Error::Full)?;
if let Some(slot) = slot {
let slot = <Backend as request::Source<C::Inputs>>::target(*slot);
if self.tuning.cancel_at(slot, Some(key)).is_break() {
let control = tuning::token::<C::Token>(slot);
let target = C::Token::tuning(control);
let complete = C::Token::cancel_tune(control);
vacant.cancel::<true>(target, complete);
return Ok(admit::Cancelled::Submitted);
}
}
vacant.cancel::<false>(C::Token::flight(key), C::Token::cancel_key(key));
Ok(admit::Cancelled::Submitted)
}
}
impl<C, S> engine::Cancel<S, <Backend as admit::Native>::Permit> for Engine<C>
where
C: ring::Context,
C::Tuning: Progress<C::Token>,
S: Into<num::NonZero<u32>>,
<C::Token as Codec>::Tuning: Tuning<Slot = S>,
{
fn cancel(&mut self, _: &<Backend as admit::Native>::Permit, slot: S) -> Result<(), Full> {
let vacancy = self.ring.submission().try_one()?;
let target = <C::Token as Codec>::Tuning::new(slot);
let index: num::NonZero<u32> = target.slot().into();
let bytes = (index.get() - 1).to_le_bytes();
let fixed = sq::Fixed::new([bytes[0], bytes[1], bytes[2]]);
let _ = self.tuning.cancel_at(fixed, None);
vacancy.cancel::<true>(C::Token::tuning(target), C::Token::cancel_tune(target));
Ok(())
}
}
impl<C: ring::Context> complete::Observe for Engine<C> {
type Observation = C::Observation;
}
impl<C: ring::Context> Close for Engine<C> {
type State = Closing<C>;
fn try_close(self) -> Result<(), Self::State> {
use dope_sys::io::socket::option::tuning::raw::Quiesce as _;
let Self { ring, tuning } = self;
match ring.try_close() {
Ok(()) => Ok(()),
Err(ring) => Err(Closing::<C>::new(ring, tuning.into_storage())),
}
}
}
impl<C: ring::Context> Shutdown for Engine<C> {
type State = owned::Closing<mappings::Region, Closing<C>>;
fn try_shutdown(self, context: <Self as engine::Buffer>::Context) -> Result<(), Self::State> {
Self::State::close(self.try_close(), context.into_region())
}
}
impl<C: ring::Context> Engine<C> {
pub const fn can_accept(&self) -> bool {
false
}
}
impl<C: ring::Context> engine::raw::Poll for Engine<C>
where
C::Tuning: Progress<C::Token>,
{
type Context = C;
type Error = <Backend as Source>::Poll;
unsafe fn wait<'a, Tag>(
&'a mut self,
quota: mem::raw::Shared<'_, Tag>,
timeout: Option<time::Duration>,
busy: bool,
) -> Result<(), Self::Error>
where
C: 'a,
{
drop(quota);
if busy || self.tuning.has_pending() || timeout.is_some_and(|span| span.is_zero()) {
self.ring.commit()
} else {
self.ring.try_wait(timeout)
}
}
}
impl<C: ring::Context> engine::raw::Register for Engine<C> {
unsafe fn register(&mut self, source: register::Source<'_>) -> Result<(), register::Error> {
let entry = <Backend as Control>::Poll::new(source, C::Token::shutdown());
let vacancy = self
.ring
.submission()
.try_one()
.map_err(register::Error::Full)?;
unsafe { submit::raw::Vacancy::borrow(vacancy, entry.entry()) }.push();
Ok(())
}
}
impl<C, const OPTIONS: usize> Engine<C>
where
C: ring::Context<Tuning = crate::driver::raw::Table<NativeKey<C>, OPTIONS>>,
{
pub fn dispatch<'d, 'p, Q, O, M, D, A, B, Tag, F, S, N, H, J>(
mode: &mut M,
quota: &mem::raw::Shared<'_, Tag>,
work: M::Work,
pending: &mut M::Pending<'p>,
observer: &O,
) -> engine::Dispatch<M::Held, <Backend as Source>::Poll, F::Fault>
where
'd: 'p,
B: native::raw::Context + 'd,
NativeSlot<C>: TryFrom<u32>,
F: host::Flight<Key = NativeKey<C>, Fault = NativeFault<C, F, S, N, H, J>>,
F::Observation: for<'a> From<&'a crate::Observed<C::Token>>,
F::AcceptFailure: From<Errno>,
F::SocketFailure: From<Create>,
S: From<native::raw::Index>,
D: host::raw::Drain<Key = NativeKey<C>, Flight<'d> = F> + 'd,
A: table::Slots<F, Index = NativeSlot<C>, Capacity = H> + AsRef<D::Driver<'d>>,
A::Retirement: reclaim::Queue<Returned = NativeReturned<C>, Class = J>,
D::Driver<'d>: buffer::Access<native::raw::Root<'d, B>, F::Exhausted, Capacity = N>,
M: Mode<'d, Q, O, Event = event::raw::Completion<'d, F>>
+ engine::raw::Owner<'d, Self, D, A>,
{
unsafe { mode.parts() }.0.ring().acquire();
let mut status = ControlFlow::Continue(());
let result = {
let mut budget = quota.lease_up_to::<event::raw::Completion<'d, F>>(quota.remaining());
{
let (_, _, _, _, _, deferred) = unsafe { mode.parts() };
if *deferred && let Some(take) = budget.take() {
take.commit();
*deferred = false;
status = M::observed(observer);
}
}
loop {
let Some(take) = budget.take() else {
break Ok(ControlFlow::Continue(()));
};
let mut input = MaybeUninit::uninit();
let mut output = MaybeUninit::uninit();
let event = {
let (backend, flights, fds, _, source, _) = unsafe { mode.parts() };
let Some(packet) =
Envelope::<'d, C, B, F>::next(slot::raw::Vacant::new(&mut input), backend)
else {
break Ok(ControlFlow::Continue(()));
};
take.commit();
let Some(mut packet) = packet else {
continue;
};
let packet = packet.get_mut();
let output = slot::raw::Vacant::new(&mut output);
match packet.deliver::<Q, O, M, D, A>(
backend,
flights,
&fds,
(source, &mut status),
observer,
output,
) {
Ok(Some(event)) => event,
Ok(None) => continue,
Err(cause) => {
packet.release(backend, fds.as_ref());
break Err(cause);
}
}
};
if let ControlFlow::Break(value) = M::emit(mode, event, work, pending) {
break Ok(ControlFlow::Break(value));
}
}
};
let (backend, _, _, _, _, _) = unsafe { mode.parts() };
let complete = backend.ring().refresh();
backend.ring().flush();
let events = match result {
Ok(ControlFlow::Break(value)) => ControlFlow::Break(value),
Ok(ControlFlow::Continue(())) => {
let pending = complete.get() != 0
|| <C::Tuning as Progress<C::Token>>::has_pending(backend.tuning());
ControlFlow::Continue(if pending {
Drain::Pending
} else {
Drain::Drained
})
}
Err(fault) => {
return Err(Failure::Completion(fault::Dispatch {
drain: Drain::Pending,
fault,
}));
}
};
Ok((events, status))
}
pub fn finish<
'd,
const STOP: bool,
const RESUME: bool,
O,
D,
A,
B,
F,
S,
N,
H,
J,
P,
K,
M,
T,
V,
X,
>(
owner: &mut O,
) -> Result<(), Cause<F::Fault, P>>
where
B: native::raw::Context + 'd,
NativeSlot<C>: TryFrom<u32>,
F: host::Flight<
Key = NativeKey<C>,
Fault = NativeFault<C, F, S, N, H, J>,
Reported = NativeReport<F, P, K, M, T, V, X>,
>,
F::Observation: for<'a> From<&'a crate::Observed<C::Token>>,
F::Fault: Copy,
F::AcceptFailure: From<Errno>,
F::SocketFailure: From<Create>,
S: From<native::raw::Index>,
X: From<Create>,
P: From<<Backend as Source>::Poll>,
D: host::raw::Drain<Key = NativeKey<C>, Flight<'d> = F, Reported = F::Reported> + 'd,
A: table::Slots<F, Index = NativeSlot<C>, Capacity = H, Physical = T, Reclaimed = V>
+ AsRef<D::Driver<'d>>,
A::Retirement: reclaim::Queue<Returned = NativeReturned<C>, Class = J>,
D::Driver<'d>: buffer::Access<native::raw::Root<'d, B>, F::Exhausted, Capacity = N>,
Self: table::Retire<'d, A::Retirement>,
F::Reported:
From<<<Self as table::Retire<'d, A::Retirement>>::Output as IntoIterator>::Item>,
O: engine::raw::Owner<'d, Self, D, A>,
{
let (backend, flights, fds, report, source, pending) = unsafe { owner.parts() };
drain::Drain {
backend,
flights,
fds,
report,
source,
pending,
}
.finish::<STOP, RESUME, B>()
}
}
impl<C: ring::Context> Engine<C>
where
C::Tuning: Progress<C::Token>,
{
pub fn commit<'d, O, D, A, Tag>(
owner: &mut O,
quota: mem::raw::Shared<'_, Tag>,
retry: bool,
) -> Result<bool, <Backend as Source>::Poll>
where
O: engine::raw::Owner<'d, Self, D, A>,
D: host::raw::Drain + 'd,
A: AsRef<D::Driver<'d>>,
D::Driver<'d>: engine::Pending,
{
let (backend, _, fds, _, _, _) = unsafe { owner.parts() };
drop(quota);
let busy = retry || fds.as_ref().has_deferred() || backend.tuning.has_pending();
backend.ring.commit()?;
Ok(busy || !backend.ring.submission().is_empty())
}
}