use super::definitions::{
CancelTimerKey, CancelTimerOptions, CLEANUP_REQUESTED,
COUNT_MASK, CURRENT_GROUP, EXIT_CONFIRMED, MAX_DEADLINE_NANOS, NATIVE_CAPACITY, OWNER_EXITED, STOPPED,
};
use super::value::SendValue;
use crate::notify::QueueNotifier;
use crate::timer::{TimerQueueError, TimerQueueStatus, TimerSubmitError};
use cordyceps::mpsc_queue::Links;
use cordyceps::Linked;
use pi_clock_manual::global::GlobalManualInstant;
use std::collections::VecDeque;
use std::num::{NonZeroU64, NonZeroUsize};
use std::ptr::NonNull;
use std::sync::atomic::{AtomicU64, AtomicUsize};
use std::sync::Arc;
pub(super) struct TimerShared<Item: 'static, N: QueueNotifier> {
queue: cordyceps::MpscQueue<TimerRequest<Item>>,
state: AtomicUsize,
publishers: [AtomicUsize; 2],
queue_id: NonZeroU64,
next_registration_id: AtomicU64,
notifier: N,
options: CancelTimerOptions,
}
static NEXT_QUEUE_ID: AtomicU64 = AtomicU64::new(1);
fn next_queue_id() -> pi_result::RawResult<NonZeroU64, TimerQueueError> {
allocate_queue_id()
}
pub(super) struct TimerRequest<Item: 'static> {
links: Links<Self>,
body: TimerRequestKind<Item>,
}
enum TimerRequestKind<Item: 'static> {
Submit {
key: CancelTimerKey,
group: bool,
deadline: GlobalManualInstant,
value: SendValue<Item>,
},
Cancel { key: CancelTimerKey },
EndOfClear { old_group: bool },
Stub,
}
#[derive(Clone, Copy)]
pub(super) struct TimerSharedSnapshot {
pub(super) count: usize,
pub(super) current_group: bool,
pub(super) stopped: bool,
pub(super) owner_exited: bool,
pub(super) cleanup_requested: bool,
pub(super) exit_confirmed: bool,
}
enum TimerSharedCleanupStep {
Progress,
Complete,
Deferred,
Busy,
}
pub(super) struct TimerPublishGuard<'a, Item: 'static, N: QueueNotifier> {
shared: &'a TimerShared<Item, N>,
group: bool,
pin_active: bool,
confirmation_needed: bool,
}
struct TimerSharedCleanupGuard<'a, Item: 'static, N: QueueNotifier> {
shared: &'a TimerShared<Item, N>,
pending: Vec<Box<TimerRequest<Item>>>,
fallback: Option<Box<TimerRequest<Item>>>,
current_debt: bool,
unsettled: usize,
armed: bool,
}
impl<Item: 'static, N: QueueNotifier> TimerShared<Item, N> {
pub(super) fn new(
notifier: N,
options: CancelTimerOptions,
) -> pi_result::Result<(Arc<Self>, Box<TimerRequest<Item>>)> {
let queue_id = next_queue_id().map_err(TimerQueueError::into_report)?;
let stub = TimerRequest::try_empty().map_err(TimerQueueError::into_report)?;
let marker = TimerRequest::try_empty().map_err(TimerQueueError::into_report)?;
Ok((timer_shared_new_inner(queue_id, notifier, options, stub), marker))
}
pub(super) fn options(&self) -> CancelTimerOptions {
timer_shared_options_inner(self)
}
pub(super) fn snapshot(&self) -> TimerSharedSnapshot {
timer_shared_snapshot_inner(self)
}
pub(super) fn status(&self) -> TimerQueueStatus {
timer_shared_status_inner(self)
}
pub(super) fn len(&self) -> usize {
timer_shared_len_inner(self)
}
pub(super) fn is_empty(&self) -> bool {
self.len() == 0
}
pub(super) fn check_key(&self, key: &CancelTimerKey) -> pi_result::RawResult<(), TimerQueueError> {
timer_check_key_inner(self, key)
}
fn prepare_submit(
&self,
deadline: GlobalManualInstant,
item: Item,
) -> pi_result::RawResult<Box<TimerRequest<Item>>, TimerSubmitError<Item>>
where
Item: Send,
{
timer_prepare_submit_inner(self, deadline, item)
}
pub(super) fn try_push(
&self,
deadline: GlobalManualInstant,
item: Item,
) -> pi_result::RawResult<CancelTimerKey, TimerSubmitError<Item>>
where
Item: Send,
{
let mut node = self.prepare_submit(deadline, item)?;
let mut publication = match TimerPublishGuard::try_new(self) {
Ok(guard) => guard,
Err(cause) => return Err(node.reject_submit(cause)),
};
if let Err(cause) = self.admit_submit(publication.group()) {
return Err(node.reject_submit(cause));
}
let key = node.set_submit_group(publication.group());
self.publish(node);
publication.published();
Ok(key)
}
pub(super) fn request_cancel(
&self,
key: &CancelTimerKey,
) -> pi_result::RawResult<(), TimerQueueError> {
let node = timer_prepare_cancel_inner(self, key)?;
let mut publication = TimerPublishGuard::try_new(self)?;
self.admit_cancel(publication.group())?;
self.publish(node);
publication.published();
Ok(())
}
pub(super) fn begin_local_submit(
&self,
) -> pi_result::RawResult<(CancelTimerKey, TimerPublishGuard<'_, Item, N>), TimerQueueError> {
let key = self.next_key()?;
let publication = TimerPublishGuard::try_new(self)?;
self.admit_submit(publication.group())?;
Ok((key, publication))
}
fn next_key(&self) -> pi_result::RawResult<CancelTimerKey, TimerQueueError> {
timer_next_key_inner(self)
}
fn admit_submit(&self, group: bool) -> pi_result::RawResult<(), TimerQueueError> {
timer_admit_submit_inner(self, group)
}
fn admit_cancel(&self, group: bool) -> pi_result::RawResult<(), TimerQueueError> {
timer_admit_cancel_inner(self, group)
}
fn publish(&self, node: Box<TimerRequest<Item>>) {
timer_publish_inner(self, node)
}
fn finish_publication(&self, group: bool) {
timer_finish_publication_inner(self, group)
}
pub(super) fn release_originals(&self, count: usize) {
timer_release_originals_inner(self, count)
}
pub(super) fn stop_accepting(&self) {
timer_stop_accepting_inner(self)
}
pub(super) fn notify(&self) {
self.notifier.notify();
}
pub(super) fn begin_owner_exit(&self) {
timer_begin_owner_exit_inner(self)
}
pub(super) fn flip_group(&self) -> bool {
timer_flip_group_inner(self)
}
pub(super) fn publishers_finished(&self, group: bool) -> bool {
timer_publishers_finished_inner(self, group)
}
pub(super) fn try_stage_requests(
&self,
target: &mut VecDeque<Box<TimerRequest<Item>>>,
limit: NonZeroUsize,
) -> pi_result::RawResult<usize, TimerQueueError> {
let result = timer_stage_requests_inner(self, target, limit);
self.confirm_exit();
result
}
pub(super) fn publish_clear_marker(
&self,
marker: Box<TimerRequest<Item>>,
old_group: bool,
) {
timer_publish_marker_inner(self, marker, old_group);
self.confirm_exit();
}
pub(super) fn try_confirm_closed(
&self,
target: &mut VecDeque<Box<TimerRequest<Item>>>,
) -> pi_result::RawResult<bool, TimerQueueError> {
let result = timer_confirm_closed_inner(self, target);
self.confirm_exit();
result
}
pub(super) fn confirm_exit(&self) {
if timer_confirm_exit_inner(self) {
self.assist_cleanup();
}
}
fn assist_cleanup(&self) {
let mut cleanup = TimerSharedCleanupGuard::new(self);
loop {
match cleanup.step() {
TimerSharedCleanupStep::Progress => continue,
TimerSharedCleanupStep::Complete
| TimerSharedCleanupStep::Deferred
| TimerSharedCleanupStep::Busy => break,
}
}
cleanup.finish();
}
}
impl<Item: 'static> TimerRequest<Item> {
fn try_empty() -> pi_result::RawResult<Box<Self>, TimerQueueError> {
timer_request_empty_inner()
}
fn set_submit_group(&mut self, group: bool) -> CancelTimerKey {
timer_request_group_inner(self, group)
}
fn reject_submit(self: Box<Self>, cause: TimerQueueError) -> TimerSubmitError<Item> {
timer_request_reject_inner(self, cause)
}
pub(super) fn submit_info(&self) -> Option<(CancelTimerKey, bool, GlobalManualInstant)> {
timer_request_submit_info_inner(self)
}
pub(super) fn take_submit(&mut self) -> Option<(CancelTimerKey, bool, GlobalManualInstant, Item)> {
timer_request_take_submit_inner(self)
}
pub(super) fn cancel_key(&self) -> Option<CancelTimerKey> {
timer_request_cancel_key_inner(self)
}
pub(super) fn take_end_of_clear(&mut self) -> Option<bool> {
timer_request_take_end_inner(self)
}
}
unsafe impl<Item: 'static> Linked<Links<Self>> for TimerRequest<Item> {
type Handle = Box<Self>;
fn into_ptr(handle: Self::Handle) -> NonNull<Self> {
timer_request_into_ptr_inner(handle)
}
unsafe fn from_ptr(ptr: NonNull<Self>) -> Self::Handle {
unsafe { timer_request_from_ptr_inner(ptr) }
}
unsafe fn links(ptr: NonNull<Self>) -> NonNull<Links<Self>> {
unsafe { timer_request_links_inner(ptr) }
}
}
impl<'a, Item: 'static, N: QueueNotifier> TimerPublishGuard<'a, Item, N> {
fn try_new(shared: &'a TimerShared<Item, N>) -> pi_result::RawResult<Self, TimerQueueError> {
timer_publication_new_inner(shared)
}
pub(super) fn group(&self) -> bool {
timer_publication_group_inner(self)
}
pub(super) fn published(&mut self) {
timer_publication_release_inner(self);
self.shared.notifier.notify();
}
}
impl<Item: 'static, N: QueueNotifier> Drop for TimerPublishGuard<'_, Item, N> {
fn drop(&mut self) {
if self.pin_active {
self.shared.finish_publication(self.group);
self.pin_active = false;
}
if self.confirmation_needed {
self.confirmation_needed = false;
self.shared.confirm_exit();
}
}
}
impl<'a, Item: 'static, N: QueueNotifier> TimerSharedCleanupGuard<'a, Item, N> {
fn new(shared: &'a TimerShared<Item, N>) -> Self {
timer_shared_guard_new_inner(shared)
}
fn step(&mut self) -> TimerSharedCleanupStep {
timer_shared_guard_step_inner(self)
}
fn finish(&mut self) {
timer_shared_guard_finish_inner(self)
}
}
impl<Item: 'static, N: QueueNotifier> Drop for TimerSharedCleanupGuard<'_, Item, N> {
fn drop(&mut self) {
timer_shared_guard_drop_inner(self)
}
}
include!("shared_inner.rs");