use crate::definitions::*;
use pi_result::RawResult as Result;
use intrusive_collections::LinkedListLink;
use std::any::TypeId;
use std::cell::{Cell, RefCell, UnsafeCell};
use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::ptr::NonNull;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize};
use std::sync::Arc;
use std::task::{RawWakerVTable, Waker};
use std::thread::ThreadId;
pub trait Schedule: Send + Sync + 'static {
fn schedule(&self, task: crate::runnable::Runnable);
}
pub trait CancelObserver: Send + Sync + 'static {
fn complete(&self, outcome: CancellationOutcome);
fn abandon(&self);
}
#[cfg(feature = "observe")]
pub trait TaskObserver: Send + Sync + 'static {
fn event(&self, task: TaskId, event: TaskEvent);
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TaskEvent {
Created,
Admitted,
PollBegin,
PollPending,
PollReady,
PollPanicked,
CancelRecorded,
PollingStopped,
FutureDropped,
ReclaimStarted,
WakerClone,
WakerWake,
WakerWakeByRef,
WakerDrop,
}
pub struct TaskOptions {
pub queue: QueueSupport,
pub capture_panic_backtrace: bool,
#[cfg(feature = "observe")]
pub observer: Option<Arc<dyn TaskObserver>>,
}
pub struct TaskThread {
id: TaskOwnerId,
thread: ThreadId,
closing: Cell<bool>,
active: Cell<usize>,
tasks: RefCell<HashMap<TaskId, TaskRef>>,
local: PhantomData<Rc<()>>,
}
pub struct TaskRegistration {
task: TaskRef,
owner: TaskOwnerId,
local: PhantomData<Rc<()>>,
}
#[repr(C)]
pub struct QueueEntry {
link: LinkedListLink,
ticket: UnsafeCell<Option<crate::runnable::Runnable>>,
}
pub struct MpscQueueEntry {
links: cordyceps::mpsc_queue::Links<Self>,
ticket: UnsafeCell<Option<crate::runnable::Runnable>>,
origin: MpscEntryOrigin,
}
#[must_use = "须移交、取回原Runnable或释放节点(node)持有"]
pub struct MpscEntryHandle {
pointer: NonNull<MpscQueueEntry>,
}
unsafe impl Send for MpscEntryHandle {}
struct LocalAndMpscLinks {
local: QueueEntry,
mpsc: MpscQueueEntry,
}
enum MpscEntryOrigin {
EmbeddedTask,
StandaloneEmpty,
}
pub(crate) struct NotifySlot<T> {
state: AtomicU8,
value: UnsafeCell<Option<T>>,
}
#[repr(C)]
pub(crate) struct Header {
state: AtomicUsize,
id: TaskId,
owner: AtomicU64,
vtable: &'static TaskVTable,
result_waiter: NotifySlot<Waker>,
cancel_waiter: NotifySlot<Arc<dyn CancelObserver>>,
cancel_wait_key: AtomicU64,
capture_panic_backtrace: bool,
#[cfg(feature = "observe")]
observer: Option<Arc<dyn TaskObserver>>,
}
pub(crate) struct TaskVTable {
run: unsafe fn(NonNull<Header>, &TaskThread) -> RunOutcome,
drop_future: unsafe fn(NonNull<Header>, Option<&TaskThread>),
destroy: unsafe fn(NonNull<Header>),
schedule: unsafe fn(NonNull<Header>, crate::runnable::Runnable),
take_result: unsafe fn(NonNull<Header>, NonNull<()>),
metadata: unsafe fn(NonNull<Header>, TypeId) -> Option<NonNull<()>>,
queue_entry: unsafe fn(NonNull<Header>) -> Option<NonNull<QueueEntry>>,
mpsc_queue_entry: unsafe fn(NonNull<Header>) -> Option<NonNull<MpscQueueEntry>>,
}
pub(crate) enum Payload<F: Future> {
Future(F),
Output(Result<F::Output, TaskError>),
Empty,
}
#[repr(C)]
pub(crate) struct TaskStorage<F: Future, S, M, L> {
header: Header,
schedule: S,
metadata: ManuallyDrop<M>,
links: L,
payload: UnsafeCell<ManuallyDrop<Payload<F>>>,
}
pub(crate) struct TaskRef {
pointer: NonNull<Header>,
}
unsafe impl Send for TaskRef {}
unsafe impl Sync for TaskRef {}
#[derive(Clone, Copy)]
struct CurrentTask {
pointer: NonNull<Header>,
id: TaskId,
}
thread_local! {
static CURRENT_TASK: Cell<Option<CurrentTask>> = const { Cell::new(None) };
}
struct CurrentGuard {
previous: Option<CurrentTask>,
previous_backtraces: Option<(TaskId, Vec<std::backtrace::Backtrace>)>,
}
struct TaskActivityGuard<'owner> {
owner: &'owner TaskThread,
}
struct RunGuard<'task> {
task: &'task TaskRef,
armed: bool,
}
struct FutureDropGuard<'header> {
header: &'header Header,
armed: bool,
}
thread_local! {
static CURRENT_PANIC_BACKTRACES: RefCell<Option<(TaskId, Vec<std::backtrace::Backtrace>)>> = const { RefCell::new(None) };
}
static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
static NEXT_OWNER_ID: AtomicU64 = AtomicU64::new(1);
const ACCESS_MASK: usize = 0b111;
const ACCESS_IDLE: usize = 0;
const ACCESS_RUNNING: usize = 1;
const ACCESS_HANDOFF: usize = 2;
const ACCESS_EXITING: usize = 3;
const ACCESS_DROPPED: usize = 4;
const ACCESS_ENDED: usize = 5;
const ACCESS_UNCONFIRMED: usize = 6;
const STARTED: usize = 1 << 3;
const WAKE_PENDING: usize = 1 << 4;
const RUNNABLE_ISSUED: usize = 1 << 5;
const CANCEL_RECORDED: usize = 1 << 6;
const ADMITTED: usize = 1 << 7;
const REASON_SHIFT: usize = 8;
const REASON_MASK: usize = 0b111 << REASON_SHIFT;
const REASON_NONE: usize = 0;
const REASON_COMPLETED: usize = 1;
const REASON_CANCELLED: usize = 2;
const REASON_PANICKED: usize = 3;
const REASON_ABANDONED: usize = 4;
const REASON_CLEANUP_FAILED: usize = 5;
const OUTPUT_PRESENT: usize = 1 << 11;
const OUTPUT_TAKEN: usize = 1 << 12;
const RESULT_INTEREST: usize = 1 << 13;
const CANCEL_WAIT_INTEREST: usize = 1 << 14;
const REF_SHIFT: usize = 15;
const REF_ONE: usize = 1 << REF_SHIFT;
const REF_MAX: usize = usize::MAX >> REF_SHIFT;
impl TaskOptions {
pub fn plain() -> Self {
options_plain_inner()
}
}
impl TaskOptions {
pub fn intrusive() -> Self {
options_intrusive_inner()
}
}
impl TaskOptions {
pub fn intrusive_mpsc() -> Self {
options_intrusive_mpsc_inner()
}
}
impl TaskOptions {
pub fn intrusive_local_and_mpsc() -> Self {
options_intrusive_local_and_mpsc_inner()
}
}
impl MpscEntryHandle {
pub fn try_from_runnable(
task: crate::runnable::Runnable,
) -> Result<Self, crate::runnable::Runnable> {
mpsc_entry_from_runnable_inner(task)
}
}
impl MpscEntryHandle {
pub fn try_into_runnable(self) -> Result<crate::runnable::Runnable, Self> {
mpsc_entry_into_runnable_inner(self)
}
}
impl MpscEntryHandle {
pub fn try_new_empty() -> pi_result::Result<Self> {
mpsc_entry_new_empty_inner()
}
}
impl Drop for MpscEntryHandle {
fn drop(&mut self) {
mpsc_entry_drop_inner(self)
}
}
unsafe impl cordyceps::Linked<cordyceps::mpsc_queue::Links<Self>> for MpscQueueEntry {
type Handle = MpscEntryHandle;
fn into_ptr(handle: Self::Handle) -> NonNull<Self> {
mpsc_linked_into_ptr_inner(handle)
}
unsafe fn from_ptr(pointer: NonNull<Self>) -> Self::Handle {
unsafe { mpsc_linked_from_ptr_inner(pointer) }
}
unsafe fn links(pointer: NonNull<Self>) -> NonNull<cordyceps::mpsc_queue::Links<Self>> {
unsafe { mpsc_linked_links_inner(pointer) }
}
}
impl TaskThread {
pub fn new() -> Self {
thread_new_inner()
}
}
impl TaskThread {
pub fn id(&self) -> TaskOwnerId {
thread_id_inner(self)
}
}
impl TaskThread {
pub fn is_closed(&self) -> bool {
thread_closed_inner(self)
}
}
impl TaskThread {
pub fn live_tasks(&self) -> usize {
thread_live_inner(self)
}
}
impl TaskThread {
pub fn close(&self) {
thread_close_inner(self)
}
}
impl Drop for TaskThread {
fn drop(&mut self) {
thread_drop_inner(self)
}
}
impl Drop for TaskRegistration {
fn drop(&mut self) {
registration_drop_inner(self)
}
}
impl TaskRef {
pub(crate) fn id(&self) -> TaskId {
ref_id_inner(self)
}
}
impl TaskRef {
pub(crate) fn snapshot(&self) -> TaskSnapshot {
ref_snapshot_inner(self)
}
}
impl TaskRef {
pub(crate) fn request_cancel(&self) {
ref_cancel_inner(self)
}
}
impl TaskRef {
pub(crate) fn waker(&self) -> Waker {
ref_waker_inner(self)
}
}
impl TaskRef {
pub(crate) fn wake(&self) {
ref_wake_inner(self)
}
}
impl TaskRef {
pub(crate) fn admit(&self, owner: &TaskThread) -> Result<TaskRegistration, AdmissionError> {
ref_admit_inner(self, owner)
}
}
impl TaskRef {
pub(crate) fn run_once(&self, owner: &TaskThread) -> Result<RunOutcome, RunErrorKind> {
ref_run_inner(self, owner)
}
}
impl TaskRef {
pub(crate) fn abandon_runnable(&self) {
ref_abandon_runnable_inner(self)
}
}
impl<'owner> TaskActivityGuard<'owner> {
fn enter(owner: &'owner TaskThread) -> Self {
task_activity_enter_inner(owner)
}
}
impl Drop for TaskActivityGuard<'_> {
fn drop(&mut self) {
task_activity_drop_inner(self)
}
}
impl Drop for RunGuard<'_> {
fn drop(&mut self) {
run_guard_drop_inner(self)
}
}
impl Drop for FutureDropGuard<'_> {
fn drop(&mut self) {
future_drop_guard_drop_inner(self)
}
}
impl TaskRef {
pub(crate) fn metadata<M: Send + Sync + 'static>(&self) -> Option<&M> {
ref_metadata_inner(self)
}
}
impl TaskRef {
pub(crate) fn register_result(&self, waker: &Waker) {
ref_register_result_inner(self, waker)
}
}
impl TaskRef {
pub(crate) fn abandon_result(&self) {
ref_abandon_result_inner(self)
}
}
impl TaskRef {
pub(crate) unsafe fn take_result<T>(&self, destination: NonNull<Result<T, TaskError>>) -> bool {
unsafe { ref_take_inner(self, destination) }
}
}
impl TaskRef {
pub(crate) fn register_cancel(
&self,
key: u64,
observer: Arc<dyn CancelObserver>,
) -> Result<(), CancellationError> {
ref_register_cancel_inner(self, key, observer)
}
}
impl TaskRef {
pub(crate) fn unregister_cancel(&self, key: u64) {
ref_unregister_cancel_inner(self, key)
}
}
impl TaskRef {
pub(crate) fn cancellation_outcome(&self) -> Option<CancellationOutcome> {
ref_cancel_outcome_inner(self)
}
}
impl TaskRef {
pub(crate) fn queue_entry(&self) -> Option<NonNull<QueueEntry>> {
ref_queue_entry_inner(self)
}
}
impl TaskRef {
pub(crate) fn mpsc_queue_entry(&self) -> Option<NonNull<MpscQueueEntry>> {
ref_mpsc_queue_entry_inner(self)
}
}
impl Clone for TaskRef {
fn clone(&self) -> Self {
ref_clone_inner(self)
}
}
impl Drop for TaskRef {
fn drop(&mut self) {
ref_drop_inner(self)
}
}
impl QueueEntry {
pub unsafe fn link_from_node(node: NonNull<Self>) -> NonNull<LinkedListLink> {
unsafe { link_from_node_inner(node) }
}
}
impl QueueEntry {
pub unsafe fn node_from_link(link: NonNull<LinkedListLink>) -> NonNull<Self> {
unsafe { node_from_link_inner(link) }
}
}
impl QueueEntry {
pub unsafe fn store(
task: crate::runnable::Runnable,
owner: TaskOwnerId,
) -> Result<NonNull<Self>, crate::runnable::Runnable> {
unsafe { queue_store_inner(task, owner) }
}
}
impl QueueEntry {
pub unsafe fn take(node: NonNull<Self>, owner: TaskOwnerId) -> crate::runnable::Runnable {
unsafe { queue_take_inner(node, owner) }
}
}
impl CurrentGuard {
unsafe fn enter(pointer: NonNull<Header>) -> Self {
unsafe { current_enter_inner(pointer) }
}
}
impl Drop for CurrentGuard {
fn drop(&mut self) {
current_guard_drop_inner(self)
}
}
pub(crate) fn current_task_id() -> Option<TaskId> {
current_task_id_inner()
}
pub fn capture_current_panic_backtrace() -> bool {
capture_current_backtrace_inner()
}
#[derive(Debug)]
pub struct PanicRecord {
pub payload: Box<dyn std::any::Any + Send + 'static>,
pub backtraces: Vec<std::backtrace::Backtrace>,
}
#[derive(Debug)]
pub enum TaskError {
Cancelled,
Abandoned,
Panicked(PanicRecord),
CleanupUnconfirmed,
OwnerClosed,
WrongThread,
AlreadyTaken,
}
pub(crate) struct CreatedRefs {
pub(crate) runnable: TaskRef,
pub(crate) control: TaskRef,
pub(crate) join: TaskRef,
}
pub(crate) fn allocate_send<F, S, M>(
future: F,
schedule: S,
metadata: M,
options: TaskOptions,
) -> Result<CreatedRefs, (F, S, M, TaskOptions, BuildErrorKind)>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
S: Schedule,
M: Send + Sync + 'static,
{
allocate_send_inner(future, schedule, metadata, options)
}
pub(crate) fn allocate_local<F, S, M>(
owner: &TaskThread,
future: F,
schedule: S,
metadata: M,
options: TaskOptions,
) -> Result<CreatedRefs, (F, S, M, TaskOptions, BuildErrorKind)>
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
{
allocate_local_inner(owner, future, schedule, metadata, options)
}
impl std::fmt::Display for TaskError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
error_display_inner(self, f)
}
}
impl std::error::Error for TaskError {}
static NATIVE_WAKER_VTABLE: RawWakerVTable =
RawWakerVTable::new(native_clone, native_wake, native_wake_by_ref, native_drop);
pub(crate) trait StorageLinks {
unsafe fn node(pointer: NonNull<Self>) -> Option<NonNull<QueueEntry>>;
unsafe fn mpsc_node(pointer: NonNull<Self>) -> Option<NonNull<MpscQueueEntry>>;
}
impl StorageLinks for () {
unsafe fn node(pointer: NonNull<Self>) -> Option<NonNull<QueueEntry>> {
unsafe { no_link_node_inner(pointer) }
}
unsafe fn mpsc_node(_pointer: NonNull<Self>) -> Option<NonNull<MpscQueueEntry>> {
None
}
}
impl StorageLinks for QueueEntry {
unsafe fn node(pointer: NonNull<Self>) -> Option<NonNull<QueueEntry>> {
unsafe { local_link_node_inner(pointer) }
}
unsafe fn mpsc_node(_pointer: NonNull<Self>) -> Option<NonNull<MpscQueueEntry>> {
None
}
}
impl StorageLinks for MpscQueueEntry {
unsafe fn node(_pointer: NonNull<Self>) -> Option<NonNull<QueueEntry>> {
None
}
unsafe fn mpsc_node(pointer: NonNull<Self>) -> Option<NonNull<MpscQueueEntry>> {
Some(pointer)
}
}
impl StorageLinks for LocalAndMpscLinks {
unsafe fn node(pointer: NonNull<Self>) -> Option<NonNull<QueueEntry>> {
Some(unsafe { NonNull::new_unchecked(std::ptr::addr_of_mut!((*pointer.as_ptr()).local)) })
}
unsafe fn mpsc_node(pointer: NonNull<Self>) -> Option<NonNull<MpscQueueEntry>> {
Some(unsafe { NonNull::new_unchecked(std::ptr::addr_of_mut!((*pointer.as_ptr()).mpsc)) })
}
}
impl<F, S, M, L> TaskStorage<F, S, M, L>
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
const VTABLE: TaskVTable = TaskVTable {
run: storage_run::<F, S, M, L>,
drop_future: storage_drop_future::<F, S, M, L>,
destroy: storage_destroy::<F, S, M, L>,
schedule: storage_schedule::<F, S, M, L>,
take_result: storage_take_result::<F, S, M, L>,
metadata: storage_metadata::<F, S, M, L>,
queue_entry: storage_queue_entry::<F, S, M, L>,
mpsc_queue_entry: storage_mpsc_queue_entry::<F, S, M, L>,
};
}
unsafe fn native_clone(pointer: *const ()) -> std::task::RawWaker {
unsafe { native_clone_inner(pointer) }
}
unsafe fn native_wake(pointer: *const ()) -> () {
unsafe { native_wake_inner(pointer) }
}
unsafe fn native_wake_by_ref(pointer: *const ()) -> () {
unsafe { native_wake_by_ref_inner(pointer) }
}
unsafe fn native_drop(pointer: *const ()) -> () {
unsafe { native_drop_inner(pointer) }
}
unsafe fn storage_run<F, S, M, L>(pointer: NonNull<Header>, owner: &TaskThread) -> RunOutcome
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_run_inner::<F, S, M, L>(pointer, owner) }
}
unsafe fn storage_drop_future<F, S, M, L>(
pointer: NonNull<Header>,
owner: Option<&TaskThread>,
) -> ()
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_drop_future_inner::<F, S, M, L>(pointer, owner) }
}
unsafe fn storage_destroy<F, S, M, L>(pointer: NonNull<Header>) -> ()
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_destroy_inner::<F, S, M, L>(pointer) }
}
unsafe fn storage_schedule<F, S, M, L>(
pointer: NonNull<Header>,
task: crate::runnable::Runnable,
) -> ()
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_schedule_inner::<F, S, M, L>(pointer, task) }
}
unsafe fn storage_take_result<F, S, M, L>(pointer: NonNull<Header>, destination: NonNull<()>) -> ()
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_take_result_inner::<F, S, M, L>(pointer, destination) }
}
unsafe fn storage_metadata<F, S, M, L>(
pointer: NonNull<Header>,
requested: TypeId,
) -> Option<NonNull<()>>
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_metadata_inner::<F, S, M, L>(pointer, requested) }
}
unsafe fn storage_queue_entry<F, S, M, L>(pointer: NonNull<Header>) -> Option<NonNull<QueueEntry>>
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_queue_entry_inner::<F, S, M, L>(pointer) }
}
unsafe fn storage_mpsc_queue_entry<F, S, M, L>(
pointer: NonNull<Header>,
) -> Option<NonNull<MpscQueueEntry>>
where
F: Future + 'static,
F::Output: 'static,
S: Schedule,
M: Send + Sync + 'static,
L: StorageLinks + 'static,
{
unsafe { storage_mpsc_queue_entry_inner::<F, S, M, L>(pointer) }
}
impl TaskRef {
pub(crate) fn is_waiting_for_wake(&self) -> bool {
ref_waiting_for_wake_inner(self)
}
}
impl TaskRegistration {
pub fn snapshot(&self) -> TaskSnapshot {
self.task.snapshot()
}
}
impl TaskRegistration {
pub fn is_waiting_for_wake(&self) -> bool {
self.task.is_waiting_for_wake()
}
}
impl TaskRegistration {
pub fn metadata<M: Send + Sync + 'static>(&self) -> Option<&M> {
self.task.metadata::<M>()
}
}
pub fn try_with_current_metadata<M: Send + Sync + 'static, R>(
read: impl FnOnce(&M) -> R,
) -> Result<R, CurrentTaskAccessError> {
current_metadata_inner::<M, R>(read)
}
pub fn try_current_task_id() -> Option<TaskId> {
current_task_id()
}
include!("task_inner.rs");