Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consolidate errors for context missing #3441

Merged
merged 38 commits into from Jan 20, 2021
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
eefa4f6
Use function to produce error string for context missing
aknuds1 Jan 17, 2021
a7b29ee
context::missing_error: Include Tokio version
aknuds1 Jan 17, 2021
5a45db8
context::missing_error: Hardcode Tokio version
aknuds1 Jan 17, 2021
68ce4af
Formatting
aknuds1 Jan 17, 2021
ed42e6e
Simplify
aknuds1 Jan 17, 2021
6f90e12
Simplify
aknuds1 Jan 17, 2021
8b26582
Appease clippy
aknuds1 Jan 17, 2021
bf2d2fc
Fix test errors
aknuds1 Jan 17, 2021
61616ad
Fix test errors
aknuds1 Jan 17, 2021
1f90f0e
Update tokio/src/util/error.rs
aknuds1 Jan 17, 2021
eef23e6
Merge remote-tracking branch 'tokio-rs/master' into chore/context-mis…
aknuds1 Jan 17, 2021
9cf7fbe
Apply feedback from review
aknuds1 Jan 17, 2021
98b50b1
Improve error messages
aknuds1 Jan 17, 2021
3126cfd
Fix tests
aknuds1 Jan 17, 2021
b2d8eb6
Fix test
aknuds1 Jan 17, 2021
18a6c13
Add integration test
aknuds1 Jan 17, 2021
5d67039
Update tokio/tests/no_rt.rs
aknuds1 Jan 17, 2021
b1f4558
Update tokio/src/time/driver/handle.rs
aknuds1 Jan 17, 2021
e62d4dd
Fix test
aknuds1 Jan 17, 2021
c707db0
Fix test
aknuds1 Jan 17, 2021
a1bbf25
Formatting
aknuds1 Jan 17, 2021
bb9530b
Add integration test
aknuds1 Jan 17, 2021
a10b386
Add integration test
aknuds1 Jan 17, 2021
d6af014
Remove argument from context_missing_error
aknuds1 Jan 17, 2021
37f613a
Remove TODO
aknuds1 Jan 17, 2021
25a5894
Clean up
aknuds1 Jan 17, 2021
37d8d8a
Use const string for context_missing_error
aknuds1 Jan 18, 2021
47ff6ef
Formatting
aknuds1 Jan 18, 2021
7602e03
Merge remote-tracking branch 'tokio-rs/master' into chore/context-mis…
aknuds1 Jan 19, 2021
0e6f644
Fixup error messages
aknuds1 Jan 19, 2021
d0d7751
Tweak error message
aknuds1 Jan 19, 2021
7abf22c
Enable usage of util::error without rt feature
aknuds1 Jan 19, 2021
3c34b95
Fix tests
aknuds1 Jan 19, 2021
8adddb1
Apply suggestions from code review
aknuds1 Jan 20, 2021
c0a7f63
io: keep track of initialized bytes in read_to_end (#3426)
Darksonn Jan 20, 2021
d88b63d
util: add pollable Semaphore (#3444)
Darksonn Jan 20, 2021
9a9244e
Merge remote-tracking branch 'tokio-rs/master' into chore/context-mis…
aknuds1 Jan 20, 2021
f4598e8
Fix tests
aknuds1 Jan 20, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 2 additions & 3 deletions tokio/src/io/driver/mod.rs
Expand Up @@ -259,8 +259,7 @@ cfg_rt! {
/// This function panics if there is no current reactor set and `rt` feature
/// flag is not enabled.
pub(super) fn current() -> Self {
crate::runtime::context::io_handle()
.expect("there is no reactor running, must be called from the context of Tokio runtime")
crate::runtime::context::io_handle().expect("io not enabled on Tokio context")
Copy link
Contributor

Choose a reason for hiding this comment

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

This error should check whether there is a runtime context or not. If there is, it should fail with an error saying that there is a runtime, but IO is disabled on it. Otherwise it should fail with the same error as the other panics.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Darksonn I made runtime::context::io_handle() fail with the standard error if the Tokio context isn't instantiated, does this address your concern or should it be implemented differently?

If runtime::context::io_handle() shouldn't panic in case of missing Tokio context, the return value has to differentiate between missing context and io being disabled.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I can't tell there being any technical drawback to have runtime::context::io_handle() panic if the Tokio context is missing.

Copy link
Contributor

Choose a reason for hiding this comment

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

It should panic in both cases, but the error messages should be different.

Copy link
Contributor Author

@aknuds1 aknuds1 Jan 17, 2021

Choose a reason for hiding this comment

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

@Darksonn I'm wondering if there might be a misunderstanding; the way I've implemented it, there are different error messages depending on whether the Tokio context is missing or io isn't enabled on it.

I implemented it so that runtime::context::io_handle will panic if the context is missing. Otherwise, io::driver::Handle::current will panic if the context doesn't have io enabled.

}
}
}
Expand All @@ -274,7 +273,7 @@ cfg_not_rt! {
/// This function panics if there is no current reactor set, or if the `rt`
/// feature flag is not enabled.
pub(super) fn current() -> Self {
panic!("there is no reactor running, must be called from the context of Tokio runtime with `rt` enabled.")
panic!(crate::util::error::context_missing_error(&[&"rt"]))
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions tokio/src/runtime/blocking/pool.rs
Expand Up @@ -9,6 +9,7 @@ use crate::runtime::builder::ThreadNameFn;
use crate::runtime::context;
use crate::runtime::task::{self, JoinHandle};
use crate::runtime::{Builder, Callback, Handle};
use crate::util::error::context_missing_error;

use std::collections::{HashMap, VecDeque};
use std::fmt;
Expand Down Expand Up @@ -81,7 +82,7 @@ where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let rt = context::current().expect("not currently running on the Tokio runtime.");
let rt = context::current().unwrap_or_else(|| panic!(context_missing_error(&[])));
rt.spawn_blocking(func)
}

Expand All @@ -91,7 +92,7 @@ where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let rt = context::current().expect("not currently running on the Tokio runtime.");
let rt = context::current().unwrap_or_else(|| panic!(context_missing_error(&[])));

let (task, _handle) = task::joinable(BlockingTask::new(func));
rt.blocking_spawner.spawn(task, &rt)
Expand Down
18 changes: 9 additions & 9 deletions tokio/src/runtime/context.rs
Expand Up @@ -13,28 +13,28 @@ pub(crate) fn current() -> Option<Handle> {

cfg_io_driver! {
pub(crate) fn io_handle() -> crate::runtime::driver::IoHandle {
CONTEXT.with(|ctx| match *ctx.borrow() {
Some(ref ctx) => ctx.io_handle.clone(),
None => Default::default(),
CONTEXT.with(|ctx| {
let ctx = ctx.borrow();
ctx.as_ref().unwrap_or_else(|| panic!(crate::util::error::context_missing_error(&[]))).io_handle.clone()
})
}
}

cfg_signal_internal! {
#[cfg(unix)]
pub(crate) fn signal_handle() -> crate::runtime::driver::SignalHandle {
CONTEXT.with(|ctx| match *ctx.borrow() {
Some(ref ctx) => ctx.signal_handle.clone(),
None => Default::default(),
CONTEXT.with(|ctx| {
let ctx = ctx.borrow();
ctx.as_ref().unwrap_or_else(|| panic!(crate::util::error::context_missing_error(&[]))).signal_handle.clone()
})
}
}

cfg_time! {
pub(crate) fn time_handle() -> crate::runtime::driver::TimeHandle {
CONTEXT.with(|ctx| match *ctx.borrow() {
Some(ref ctx) => ctx.time_handle.clone(),
None => Default::default(),
CONTEXT.with(|ctx| {
let ctx = ctx.borrow();
ctx.as_ref().unwrap_or_else(|| panic!(crate::util::error::context_missing_error(&[]))).time_handle.clone()
})
}

Expand Down
5 changes: 3 additions & 2 deletions tokio/src/runtime/handle.rs
@@ -1,6 +1,7 @@
use crate::runtime::blocking::task::BlockingTask;
use crate::runtime::task::{self, JoinHandle};
use crate::runtime::{blocking, context, driver, Spawner};
use crate::util::error::context_missing_error;

use std::future::Future;
use std::{error, fmt};
Expand Down Expand Up @@ -97,7 +98,7 @@ impl Handle {
/// # }
/// ```
pub fn current() -> Self {
context::current().expect("not currently running on the Tokio runtime.")
context::current().unwrap_or_else(|| panic!(context_missing_error(&[])))
}

/// Returns a Handle view over the currently running Runtime
Expand Down Expand Up @@ -213,7 +214,7 @@ impl fmt::Debug for TryCurrentError {

impl fmt::Display for TryCurrentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("no tokio Runtime has been initialized")
f.write_str(&context_missing_error(&[]))
}
}

Expand Down
3 changes: 2 additions & 1 deletion tokio/src/task/spawn.rs
@@ -1,5 +1,6 @@
use crate::runtime;
use crate::task::JoinHandle;
use crate::util::error::context_missing_error;

use std::future::Future;

Expand Down Expand Up @@ -129,7 +130,7 @@ cfg_rt! {
T::Output: Send + 'static,
{
let spawn_handle = runtime::context::spawn_handle()
.expect("must be called from the context of Tokio runtime configured with either `basic_scheduler` or `threaded_scheduler`");
.unwrap_or_else(|| panic!(context_missing_error(&[])));
let task = crate::util::trace::task(task, "task");
spawn_handle.spawn(task)
}
Expand Down
5 changes: 2 additions & 3 deletions tokio/src/time/driver/handle.rs
Expand Up @@ -47,7 +47,7 @@ cfg_rt! {
/// panicking.
pub(crate) fn current() -> Self {
crate::runtime::context::time_handle()
.expect("there is no timer running, must be called from the context of Tokio runtime")
.expect("time must be enabled on the Tokio 1.x context")
aknuds1 marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand All @@ -71,8 +71,7 @@ cfg_not_rt! {
/// lazy, and so outside executed inside the runtime successfuly without
/// panicking.
pub(crate) fn current() -> Self {
panic!("there is no timer running, must be called from the context of Tokio runtime or \
`rt` is not enabled")
panic!("`rt` must be enabled")
Copy link
Contributor

Choose a reason for hiding this comment

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

This should be using the standardized error message, no?

Copy link
Contributor Author

@aknuds1 aknuds1 Jan 17, 2021

Choose a reason for hiding this comment

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

@Darksonn Isn't the difference here that the rt feature is disabled? It isn't just that the context hasn't been instantiated.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, here the rt feature needs to be enabled.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Darksonn but you're suggesting this error message should change? I'm not following.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Can you provide a code change suggestion, if you have something in mind?

Copy link
Contributor

Choose a reason for hiding this comment

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

Sure.

panic!(context_missing_error(&["rt"]));

In fact, you do not currently use the list argument anywhere.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Darksonn OK, I figured it was kind of pointless to produce an error saying that there's no reactor running since the runtime isn't compiled in in the first place (due to the "rt" feature being disabled).

Copy link
Contributor

Choose a reason for hiding this comment

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

You are free to pick another wording, but "rt must be enabled" is too short. It needs to mention that this is a Tokio feature, including the Tokio version.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Darksonn Please see my updated error string.

}
}
}
Expand Down
61 changes: 61 additions & 0 deletions tokio/src/util/error.rs
@@ -0,0 +1,61 @@
use std::fmt::Write;

/// Returns an error string explaining that the Tokio context hasn't been instantiated.
pub(crate) fn context_missing_error(features: &[&str]) -> String {
// TODO: Include Tokio version
let sfx = if !features.is_empty() {
let mut sfx = String::from(" with ");
for (i, feat) in features.iter().enumerate() {
if i == 0 {
if features.len() > 1 {
write!(&mut sfx, "either ").expect("failed to write to string");
}
} else if i == features.len() - 1 {
write!(&mut sfx, " or ").expect("failed to write to string");
} else {
write!(&mut sfx, ", ").expect("failed to write to string");
}
write!(&mut sfx, "{}", feat).expect("failed to write to string");
}
write!(&mut sfx, " enabled").expect("failed to write to string");
sfx
} else {
String::new()
};
format!(
"there is no reactor running, must be called from the context of a Tokio 1.x runtime{}",
sfx
)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_context_missing_error_no_features() {
assert_eq!(
&context_missing_error(&[]),
"there is no reactor running, must be called from the context of a Tokio 1.x runtime"
);
}

#[test]
fn test_context_missing_error_one_feature() {
assert_eq!(&context_missing_error(&["rt"]),
"there is no reactor running, must be called from the context of a Tokio 1.x runtime with rt enabled");
}

#[test]
fn test_context_missing_error_two_features() {
assert_eq!(&context_missing_error(&["rt", "signal"]),
"there is no reactor running, must be called from the context of a Tokio 1.x runtime with either rt or signal enabled");
}

#[test]
fn test_context_missing_error_three_features() {
assert_eq!(&context_missing_error(&["rt", "signal", "sync"]),
"there is no reactor running, must be called from the context of a Tokio 1.x runtime with either rt, signal or sync enabled"
);
}
}
3 changes: 3 additions & 0 deletions tokio/src/util/mod.rs
Expand Up @@ -35,3 +35,6 @@ pub(crate) mod trace;
#[cfg(any(feature = "macros"))]
#[cfg_attr(not(feature = "macros"), allow(unreachable_pub))]
pub use rand::thread_rng_n;

#[cfg(any(feature = "rt", feature = "net"))]
pub(crate) mod error;
4 changes: 2 additions & 2 deletions tokio/tests/no_rt.rs
Expand Up @@ -7,8 +7,8 @@ use futures::executor::block_on;
use std::net::TcpListener;

#[test]
#[should_panic(expected = "no timer running")]
fn panics_when_no_timer() {
#[should_panic(expected = "no reactor running")]
aknuds1 marked this conversation as resolved.
Show resolved Hide resolved
fn timeout_panics_when_no_tokio_context() {
block_on(timeout_value());
}

Expand Down
15 changes: 14 additions & 1 deletion tokio/tests/rt_basic.rs
Expand Up @@ -6,7 +6,7 @@ use tokio::sync::oneshot;
use tokio_test::{assert_err, assert_ok};

use std::thread;
use std::time::Duration;
use tokio::time::{timeout, Duration};

mod support {
pub(crate) mod mpsc_stream;
Expand Down Expand Up @@ -135,6 +135,19 @@ fn acquire_mutex_in_drop() {
drop(rt);
}

#[test]
#[should_panic(expected = "time must be enabled on the Tokio 1.x context")]
fn timeout_panics_when_no_time_handle() {
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
rt.block_on(async {
let (_tx, rx) = oneshot::channel::<()>();
let dur = Duration::from_millis(20);
let _ = timeout(dur, rx).await;
});
}

fn rt() -> Runtime {
tokio::runtime::Builder::new_current_thread()
.enable_all()
Expand Down