Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "panicked at 'not currently running on the Tokio runtime'" when using block_on from the futures crate?

I'm using the example code on elastic search's blog post about their new crate and I'm unable to get it working as intended. The thread panics with thread 'main' panicked at 'not currently running on the Tokio runtime.'.

What is the Tokio runtime, how do I configure it and why must I?

use futures::executor::block_on;

async elastic_search_example() -> Result<(), Box<dyn Error>> {
    let index_response = client
        .index(IndexParts::IndexId("tweets", "1"))
        .body(json!({
            "user": "kimchy",
            "post_date": "2009-11-15T00:00:00Z",
            "message": "Trying out Elasticsearch, so far so good?"
        }))
        .refresh(Refresh::WaitFor)
        .send()
        .await?;
    if !index_response.status_code().is_success() {
        panic!("indexing document failed")
    }
    let index_response = client
        .index(IndexParts::IndexId("tweets", "2"))
        .body(json!({
            "user": "forloop",
            "post_date": "2020-01-08T00:00:00Z",
            "message": "Indexing with the rust client, yeah!"
        }))
        .refresh(Refresh::WaitFor)
        .send()
        .await?;
    if !index_response.status_code().is_success() {
        panic!("indexing document failed")
    }
}

fn main() {
    block_on(elastic_search_example());
}
like image 523
Miranda Abbasi Avatar asked Jan 16 '20 04:01

Miranda Abbasi


2 Answers

It looks like Elasticsearch's crate is using Tokio internally, so you must use it too to match their assumptions.

Looking for block_on function in their documentation, I've got this. So, it appears that your main should look like this:

use tokio::runtime::Runtime;

fn main() {
    Runtime::new()
        .expect("Failed to create Tokio runtime")
        .block_on(elastic_search_example());
}

Or you can make you main function itself async with the attribute macro, which will generate runtime creation and block_on call for you:

#[tokio::main]
async fn main() {
    elastic_search_example().await;
}
like image 121
Cerberus Avatar answered Nov 01 '22 16:11

Cerberus


I had the same error when I used to tokio::run (from tokio version = 0.1) with crate that use tokio02 (tokio version = 0.2) internally (in my case it was reqwest). First I just changed std::future::Future to futures01::future::Future with futures03::compat. To make it compile. After run I get exactly your error.

Solution:

Adding tokio-compat resolved my problem.


More about tokio compat

like image 40
S.R Avatar answered Nov 01 '22 18:11

S.R