Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions tests-build/tests/fail/macros_invalid_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,7 @@ async fn test_has_second_test_attr_rust_2021() {}
#[tokio::test]
async fn test_has_generated_second_test_attr() {}

#[tokio::test(name = 123)]
async fn test_name_not_string() {}

fn main() {}
12 changes: 9 additions & 3 deletions tests-build/tests/fail/macros_invalid_input.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ error: the `async` keyword is missing from the function declaration
6 | fn main_is_not_async() {}
| ^^

error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`.
error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`, `name`.
--> tests/fail/macros_invalid_input.rs:8:15
|
8 | #[tokio::main(foo)]
Expand All @@ -22,13 +22,13 @@ error: the `async` keyword is missing from the function declaration
15 | fn test_is_not_async() {}
| ^^

error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`.
error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`, `name`.
--> tests/fail/macros_invalid_input.rs:17:15
|
17 | #[tokio::test(foo)]
| ^^^

error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`
error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`, `name`.
--> tests/fail/macros_invalid_input.rs:20:15
|
20 | #[tokio::test(foo = 123)]
Expand Down Expand Up @@ -119,3 +119,9 @@ error: second test attribute is supplied, consider removing or changing the orde
| ^^^^^^^^^^^^^^
|
= note: this error originates in the attribute macro `tokio::test` (in Nightly builds, run with -Z macro-backtrace for more info)

error: Failed to parse value of `name` as string.
--> tests/fail/macros_invalid_input.rs:71:22
|
71 | #[tokio::test(name = 123)]
| ^^^
2 changes: 1 addition & 1 deletion tokio-macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ quote = "1"
syn = { version = "2.0", features = ["full"] }

[dev-dependencies]
tokio = { version = "1.0.0", features = ["full", "test-util"] }
tokio = { version = "1.0.0", path = "../tokio", features = ["full", "test-util"] }
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant path dependency accidentally committed

Low Severity

The workspace root Cargo.toml already has [patch.crates-io] tokio = { path = "tokio" }, which automatically redirects all workspace members' tokio dependency to the local path. Adding an explicit path = "../tokio" to tokio-macros's [dev-dependencies] is therefore redundant. Notably, the tokio-macros/Cargo.toml header comment itself says "Remove path dependencies (if any)" before releasing, suggesting this was a local debugging artifact that wasn't cleaned up.

Fix in Cursor Fix in Web

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

value:annoying; category:bug; feedback: The Bugbot AI reviewer is not correct! The patch is used by most of the CI checks but some of them remove it to test a "pre-release". The "path" setting is needed for those pre-release checks.


[package.metadata.docs.rs]
all-features = true
Expand Down
28 changes: 25 additions & 3 deletions tokio-macros/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ impl UnhandledPanic {
}

struct FinalConfig {
name: Option<String>,
flavor: RuntimeFlavor,
worker_threads: Option<usize>,
start_paused: Option<bool>,
Expand All @@ -62,6 +63,7 @@ struct FinalConfig {

/// Config used in case of the attribute not being able to build a valid config
const DEFAULT_ERROR_CONFIG: FinalConfig = FinalConfig {
name: None,
flavor: RuntimeFlavor::CurrentThread,
worker_threads: None,
start_paused: None,
Expand All @@ -70,6 +72,7 @@ const DEFAULT_ERROR_CONFIG: FinalConfig = FinalConfig {
};

struct Configuration {
name: Option<String>,
rt_multi_thread_available: bool,
default_flavor: RuntimeFlavor,
flavor: Option<RuntimeFlavor>,
Expand All @@ -83,6 +86,7 @@ struct Configuration {
impl Configuration {
fn new(is_test: bool, rt_multi_thread: bool) -> Self {
Configuration {
name: None,
rt_multi_thread_available: rt_multi_thread,
default_flavor: match is_test {
true => RuntimeFlavor::CurrentThread,
Expand All @@ -97,6 +101,16 @@ impl Configuration {
}
}

fn set_name(&mut self, name: syn::Lit, span: Span) -> Result<(), syn::Error> {
if self.name.is_some() {
return Err(syn::Error::new(span, "`name` set multiple times."));
}

let runtime_name = parse_string(name, span, "name")?;
self.name = Some(runtime_name);
Ok(())
}

fn set_flavor(&mut self, runtime: syn::Lit, span: Span) -> Result<(), syn::Error> {
if self.flavor.is_some() {
return Err(syn::Error::new(span, "`flavor` set multiple times."));
Expand Down Expand Up @@ -227,6 +241,7 @@ impl Configuration {
};

Ok(FinalConfig {
name: self.name.clone(),
crate_name: self.crate_name.clone(),
flavor,
worker_threads,
Expand Down Expand Up @@ -372,9 +387,12 @@ fn build_config(
config
.set_unhandled_panic(lit.clone(), syn::spanned::Spanned::span(lit))?;
}
"name" => {
config.set_name(lit.clone(), syn::spanned::Spanned::span(lit))?;
}
name => {
let msg = format!(
"Unknown attribute {name} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`",
"Unknown attribute {name} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`, `name`.",
);
return Err(syn::Error::new_spanned(namevalue, msg));
}
Expand All @@ -397,11 +415,12 @@ fn build_config(
"Set the runtime flavor with #[{macro_name}(flavor = \"current_thread\")]."
)
}
"flavor" | "worker_threads" | "start_paused" | "crate" | "unhandled_panic" => {
"flavor" | "worker_threads" | "start_paused" | "crate" | "unhandled_panic"
| "name" => {
format!("The `{name}` attribute requires an argument.")
}
name => {
format!("Unknown attribute {name} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`.")
format!("Unknown attribute {name} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`, `name`.")
}
};
return Err(syn::Error::new_spanned(path, msg));
Expand Down Expand Up @@ -478,6 +497,9 @@ fn parse_knobs(mut input: ItemFn, is_test: bool, config: FinalConfig) -> TokenSt
let unhandled_panic = v.into_tokens(&crate_path);
rt = quote_spanned! {last_stmt_start_span=> #rt.unhandled_panic(#unhandled_panic) };
}
if let Some(v) = config.name {
rt = quote_spanned! {last_stmt_start_span=> #rt.name(#v) };
}

let generated_attrs = if is_test {
quote! {
Expand Down
49 changes: 49 additions & 0 deletions tokio-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,30 @@ use proc_macro::TokenStream;
///
/// # Usage
///
/// ## Set the name of the runtime
///
/// ```rust
/// #[tokio::main(name = "my-runtime")]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
/// tokio::runtime::Builder::new_multi_thread()
/// .enable_all()
/// .name("my-runtime")
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ## Using the multi-threaded runtime
///
/// ```rust
Expand Down Expand Up @@ -408,6 +432,31 @@ pub fn main_rt(args: TokenStream, item: TokenStream) -> TokenStream {
///
/// ## Usage
///
/// ### Set the name of the runtime
///
/// ```no_run
/// #[tokio::test(name = "my-test-runtime")]
/// async fn my_test() {
/// assert!(true);
/// }
/// ```
///
/// Equivalent code not using `#[tokio::test]`
///
/// ```no_run
/// #[test]
/// fn my_test() {
/// tokio::runtime::Builder::new_current_thread()
/// .enable_all()
/// .name("my-test-runtime")
/// .build()
/// .unwrap()
/// .block_on(async {
/// assert!(true);
/// })
/// }
/// ```
///
/// ### Using the multi-thread runtime
///
/// ```no_run
Expand Down
30 changes: 30 additions & 0 deletions tokio/src/runtime/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ pub struct Builder {
/// Runtime type
kind: Kind,

/// Name of the runtime.
name: Option<String>,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Builder now has a name configuration, but impl fmt::Debug for Builder doesn’t include it, which can make debug output misleading when diagnosing runtime configuration. Consider including the name field in the debug struct output as well.

Severity: low

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

value:good-to-have; category:bug; feedback: The Augment AI reviewer is correct! There is a custom implementation of std::fmt::Debug trait and the new name field is not added to it. Prevents missing to print the name of the runtime in its Debug implementation.


/// Whether or not to enable the I/O driver
enable_io: bool,
nevents: usize,
Expand Down Expand Up @@ -271,6 +274,9 @@ impl Builder {
Builder {
kind,

// Default runtime name
name: None,

// I/O defaults to "off"
enable_io: false,
nevents: 1024,
Expand Down Expand Up @@ -538,6 +544,28 @@ impl Builder {
self
}

/// Sets the name of the runtime.
///
/// # Examples
///
/// ```
/// # #[cfg(not(target_family = "wasm"))]
/// # {
/// # use tokio::runtime;
///
/// # pub fn main() {
/// let rt = runtime::Builder::new_multi_thread()
/// .name("my-runtime")
/// .build();
/// # }
/// # }
/// ```
pub fn name(&mut self, val: impl Into<String>) -> &mut Self {
let val = val.into();
self.name = Some(val);
self
}

/// Sets a function used to generate the name of threads spawned by the `Runtime`'s thread pool.
///
/// The default name fn is `|| "tokio-rt-worker".into()`.
Expand Down Expand Up @@ -1633,6 +1661,7 @@ impl Builder {
metrics_poll_count_histogram: self.metrics_poll_count_histogram_builder(),
},
local_tid,
self.name.clone(),
);

let handle = Handle {
Expand Down Expand Up @@ -1814,6 +1843,7 @@ cfg_rt_multi_thread! {
metrics_poll_count_histogram: self.metrics_poll_count_histogram_builder(),
},
self.timer_flavor,
self.name.clone(),
);

let handle = Handle { inner: scheduler::Handle::MultiThread(handle) };
Expand Down
21 changes: 21 additions & 0 deletions tokio/src/runtime/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,27 @@ impl Handle {
runtime::Id::new(owned_id)
}

/// Returns the name of the current `Runtime`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main(flavor = "current_thread", name = "my-runtime")]
/// async fn main() {
/// println!("Current runtime name: {}", Handle::current().name().unwrap());
/// }
/// ```
///
pub fn name(&self) -> Option<&str> {
match &self.inner {
scheduler::Handle::CurrentThread(handle) => handle.name(),
#[cfg(feature = "rt-multi-thread")]
scheduler::Handle::MultiThread(handle) => handle.name(),
}
}

/// Returns a view that lets you get information about how the runtime
/// is performing.
pub fn metrics(&self) -> RuntimeMetrics {
Expand Down
9 changes: 9 additions & 0 deletions tokio/src/runtime/scheduler/current_thread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ pub(crate) struct CurrentThread {

/// Handle to the current thread scheduler
pub(crate) struct Handle {
/// The name of the runtime
pub(crate) name: Option<String>,

/// Scheduler state shared across threads
shared: Shared,

Expand Down Expand Up @@ -132,6 +135,7 @@ impl CurrentThread {
seed_generator: RngSeedGenerator,
config: Config,
local_tid: Option<ThreadId>,
name: Option<String>,
) -> (CurrentThread, Arc<Handle>) {
let worker_metrics = WorkerMetrics::from_config(&config);
worker_metrics.set_thread_id(thread::current().id());
Expand All @@ -142,6 +146,7 @@ impl CurrentThread {
.unwrap_or(DEFAULT_GLOBAL_QUEUE_INTERVAL);

let handle = Arc::new(Handle {
name,
task_hooks: TaskHooks {
task_spawn_callback: config.before_spawn.clone(),
task_terminate_callback: config.after_termination.clone(),
Expand Down Expand Up @@ -639,6 +644,10 @@ impl Handle {
pub(crate) fn owned_id(&self) -> NonZeroU64 {
self.shared.owned.id
}

pub(crate) fn name(&self) -> Option<&str> {
self.name.as_deref()
}
}

impl fmt::Debug for Handle {
Expand Down
7 changes: 7 additions & 0 deletions tokio/src/runtime/scheduler/multi_thread/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ use crate::loom::sync::atomic::{AtomicBool, Ordering::SeqCst};

/// Handle to the multi thread scheduler
pub(crate) struct Handle {
/// The name of the runtime
pub(crate) name: Option<String>,

/// Task spawner
pub(super) shared: worker::Shared,

Expand Down Expand Up @@ -123,6 +126,10 @@ impl Handle {
pub(crate) fn owned_id(&self) -> NonZeroU64 {
self.shared.owned.id
}

pub(crate) fn name(&self) -> Option<&str> {
self.name.as_deref()
}
}

impl fmt::Debug for Handle {
Expand Down
3 changes: 3 additions & 0 deletions tokio/src/runtime/scheduler/multi_thread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub(crate) struct MultiThread;
// ===== impl MultiThread =====

impl MultiThread {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
size: usize,
driver: Driver,
Expand All @@ -62,6 +63,7 @@ impl MultiThread {
seed_generator: RngSeedGenerator,
config: Config,
timer_flavor: TimerFlavor,
name: Option<String>,
) -> (MultiThread, Arc<Handle>, Launch) {
let parker = Parker::new(driver);
let (handle, launch) = worker::create(
Expand All @@ -72,6 +74,7 @@ impl MultiThread {
seed_generator,
config,
timer_flavor,
name,
);

(MultiThread, handle, launch)
Expand Down
Loading