vthread 0.1.0

Bounded carrier-affine virtual threads for Rust
Documentation
//! Typed task completion handles.

use std::{fmt, sync::Arc};

use crate::{Error, PanicReport, Result, TaskId, context, control::Shared, task::SharedTaskRecord};

pub(crate) struct JoinCell<T> {
    pub(crate) outcome: Option<std::result::Result<T, PanicReport>>,
}

pub(crate) trait JoinOutcome<T>: Send + Sync {
    fn take(&self) -> Option<std::result::Result<T, PanicReport>>;
}

/// A typed result handle whose completion follows carrier-side stack reclamation.
#[must_use = "observe the result or explicitly drop it; the scope still owns the task"]
pub struct JoinHandle<T> {
    shared: Arc<Shared>,
    id: TaskId,
    cell: Arc<dyn JoinOutcome<T>>,
    record: SharedTaskRecord,
    taken: bool,
}

impl<T> JoinHandle<T> {
    pub(crate) fn new(
        shared: Arc<Shared>,
        id: TaskId,
        cell: Arc<dyn JoinOutcome<T>>,
        record: SharedTaskRecord,
    ) -> Self {
        Self {
            shared,
            id,
            cell,
            record,
            taken: false,
        }
    }

    /// Returns the task identity.
    pub fn task_id(&self) -> TaskId {
        self.id
    }

    /// Returns this child's token; cancelling it affects descendants, not its siblings.
    pub fn cancellation_token(&self) -> crate::CancellationToken {
        self.record.lock().options().cancellation.clone()
    }

    /// Requests cooperative child cancellation without consuming its result handle.
    pub fn cancel(&self) {
        self.cancellation_token().cancel();
    }

    /// Returns whether the task has reached a terminal state.
    pub fn is_finished(&self) -> bool {
        self.record.completion().done()
    }

    /// Waits without consuming observation ownership. Cancellation/deadlines are retryable.
    /// A completed handle returns immediately, even after its result was consumed or
    /// its diagnostic record was evicted, without checking the caller's cancellation.
    /// While parked, the selected completion/cancellation/deadline winner is final;
    /// policy arriving after completion is observed at the next cooperative boundary.
    pub fn wait(&mut self) -> Result<()> {
        if self.is_finished() {
            return Ok(());
        }
        if context::current().is_some() {
            crate::join_wait::wait_for(
                &self.record,
                crate::SuspensionReason::Join(self.id),
                false,
            )?;
        } else {
            let scope = self.record.lock().scope;
            self.shared.wait(scope, Some(&self.record))?;
        }
        Ok(())
    }

    /// Waits for reclamation and takes the result once; interruption retains the handle.
    pub fn join(&mut self) -> Result<T> {
        if self.taken {
            return Err(Error::ResultAlreadyTaken);
        }
        self.wait()?;
        self.take_result()
    }

    /// Takes a finished result without waiting or checking the caller's cancellation.
    /// Returns WouldBlock while unfinished, or ResultAlreadyTaken after consumption.
    pub fn take_result(&mut self) -> Result<T> {
        if self.taken {
            return Err(Error::ResultAlreadyTaken);
        }
        if !self.is_finished() {
            return Err(Error::WouldBlock);
        }
        self.taken = true;
        let (failure, panic) = {
            let mut record = self.record.lock();
            record.outcome_observed = true;
            (record.failure, record.panic.clone())
        };
        if let Some(reason) = failure {
            return Err(Error::TaskAborted {
                task: self.id,
                reason,
            });
        }
        if let Some(panic) = panic {
            let name = self.record.lock().name.to_string();
            return Err(Error::task_panicked(self.id, name, panic));
        }
        let outcome = self.cell.take().ok_or_else(|| {
            Error::fault(
                crate::error::FaultComponent::Scheduler,
                "completed task has no join outcome",
            )
        })?;
        outcome.map_err(|panic| {
            let name = self.record.lock().name.to_string();
            Error::task_panicked(self.id, name, panic)
        })
    }
}

impl<T> fmt::Debug for JoinHandle<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let record = self.record.lock();
        formatter
            .debug_struct("JoinHandle")
            .field("id", &self.id)
            .field("name", &record.name)
            .field("status", &record.status)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
#[path = "join_test.rs"]
mod join_test;

#[cfg(test)]
#[path = "join_commit_test.rs"]
mod join_commit_test;