Repository: tokio-rs/tokio
File: tokio/src/runtime/task/mod.rs (Rust)

Code before:
/// An opaque ID that uniquely identifies a task relative to all other currently
/// running tasks.
///
/// # Notes
///
/// - Task IDs are unique relative to other *currently running* tasks. When a
///   task completes, the same ID may be used for another task.
/// - Task IDs are *not* sequential, and do not indicate the order in which
///   tasks are spawned, what runtime a task is spawned on, or any other data.
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// [unstable]: crate#unstable-features
#[cfg_attr(docsrs, doc(cfg(all(feature = "rt", tokio_unstable))))]
#[cfg_attr(not(tokio_unstable), allow(unreachable_pub))]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub struct Id(u64);

use crate::runtime::context;

/// Returns the `Id` of the task.
///
/// # Panics
///
/// This function panics if called from outside a task or if called from a
/// future passed to `block_on` call.
///
#[cfg_attr(not(tokio_unstable), allow(unreachable_pub))]
#[track_caller]
pub fn id() -> Id {
    use crate::runtime::context;
    context::current_task_id()
}

/// Guard that sets and clears the task id in the context during task execution
/// and cancellation.
pub(crate) struct TaskIdGuard {}
impl TaskIdGuard {
    fn new(id: Id) -> Self {
        context::set_current_task_id(Some(id));
        TaskIdGuard {}
    }
}
impl Drop for TaskIdGuard {
    fn drop(&mut self) {
        context::set_current_task_id(None);
    }
}


Review comment (suggestion):
I'm not sure how I feel about this method always panicking if called outside of a task context. I think there should be a way to get an `Option<Id>` that returns `None` if outside of a task context. That would be useful for code that may be called outside of a task, such as a logger that wants to display the current task ID if inside of a task, or not display anything if running outside of a task or in `block_on`.

Perhaps we should either change this to return `Option<Id>`, or add a `fn try_id() -> Option<Id>` (or something like that --- we can bikeshed over the naming).

Code after:
use std::{fmt, mem};

/// An opaque ID that uniquely identifies a task relative to all other currently
/// running tasks.
///
/// # Notes
///
/// - Task IDs are unique relative to other *currently running* tasks. When a
///   task completes, the same ID may be used for another task.
/// - Task IDs are *not* sequential, and do not indicate the order in which
///   tasks are spawned, what runtime a task is spawned on, or any other data.
/// - The task ID of the currently running task can be obtained from inside the
///   task via the [`task::try_id()`](crate::task::try_id()) and
///   [`task::id()`](crate::task::id()) functions and from outside the task via
///   the [`JoinHandle::id()`](crate::task::JoinHandle::id()) function.
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// [unstable]: crate#unstable-features
#[cfg_attr(docsrs, doc(cfg(all(feature = "rt", tokio_unstable))))]
#[cfg_attr(not(tokio_unstable), allow(unreachable_pub))]
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub struct Id(u64);

/// Returns the [`Id`] of the currently running task.
///
/// # Panics
///
/// This function panics if called from outside a task. Please note that calls
/// to `block_on` do not have task IDs, so the method will panic if called from
/// within a call to `block_on`. For a version of this function that doesn't
/// panic, see [`task::try_id()`](crate::runtime::task::try_id()).
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// [task ID]: crate::task::Id
/// [unstable]: crate#unstable-features
#[cfg_attr(not(tokio_unstable), allow(unreachable_pub))]
#[track_caller]
pub fn id() -> Id {
    context::current_task_id().expect("Can't get a task id when not inside a task")
}

/// Returns the [`Id`] of the currently running task, or `None` if called outside
/// of a task.
///
/// This function is similar to  [`task::id()`](crate::runtime::task::id()), except