将新任务添加到 tokio 事件循环并在失败时重试任务

Add new tasks to tokio event loop and retry tasks on failure

我正在尝试编写一个可以从同一服务器执行获取请求的 tokio 事件循环,具有以下特点:

到目前为止,在我的尝试中,我已经设法让这 4 个项目的不同组合起作用,但从来没有在一起。我的主要问题是我不太明白如何向 tokio 事件循环添加新的期货。

我假设我需要将 loop_fn 用于轮询接收器的主循环,并使用 handle.spawn 来生成新任务? handle.spawn 只允许 Result<(),()> 的未来,所以我不能使用它的输出在失败时重生作业,所以我需要将重试检查移到那个未来?

下面是批量接受和处理 url 的尝试(因此没有连续轮询),并且有超时(但没有重试):

fn place_dls(&mut self, reqs: Vec<String>) {
    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let timeout = Timeout::new(Duration::from_millis(5000), &handle).unwrap();

    let send_dls = stream::iter_ok::<_, reqwest::Error>(reqs.iter().map(|o| {
        // send with request through an async reqwest client in self
    }));

    let rec_dls = send_dls.buffer_unordered(dls.len()).for_each(|n| {
        n.into_body().concat2().and_then(|full_body| {
            debug!("Received: {:#?}", full_body);

            // TODO: how to put the download back in the queue if failure code is received?
        })
    });

    let work = rec_dls.select2(timeout).then(|res| match res {
        Ok(Either::A((got, _timeout))) => {
            Ok(got)
        },
        Ok(Either::B((_timeout_error, _get))) => {
            // TODO: put back in queue
            Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "Client timed out while connecting",
            ).into())
        }
        Err(Either::A((get_error, _timeout))) => Err(get_error.into()),
        Err(Either::B((timeout_error, _get))) => Err(timeout_error.into()),
    });

    core.run(work);
}

我对 loop_fn 的尝试不幸地失败了。

I assume I need to use loop_fn for the main loop

我稍微建议另一种方法:实现 futures::sync::mpsc::Receiver 流消费者而不是循环。

它可以被视为某种主进程:在通过 Receiver 接收到 url 之后,可以生成 tokio 任务来下载内容。然后重试就没有问题了:只需将失败或超时的 url 通过其 Sender 端点再次发送到主通道即可。

这是一个工作代码草图:

extern crate futures;
extern crate tokio;

use std::{io, time::{Duration, Instant}};
use futures::{
    Sink,
    Stream,
    stream,
    sync::mpsc,
    future::Future,
};
use tokio::{
    runtime::Runtime,
    timer::{Delay, Timeout},
};

fn main() -> Result<(), io::Error> {
    let mut rt = Runtime::new()?;
    let executor = rt.executor();

    let (tx, rx) = mpsc::channel(0);
    let master_tx = tx.clone();
    let master = rx.for_each(move |url: String| {
        let download_future = download(&url)
            .map(|_download_contents| {
                // TODO: actually do smth with contents
                ()
            });
        let timeout_future =
            Timeout::new(download_future, Duration::from_millis(2000));
        let job_tx = master_tx.clone();
        let task = timeout_future
            .or_else(move |error| {
                // actually download error or timeout, retry
                println!("retrying {} because of {:?}", url, error);
                job_tx.send(url).map(|_| ()).map_err(|_| ())
            });
        executor.spawn(task);
        Ok(())
    });

    rt.spawn(master);

    let urls = vec![
        "http://url1".to_string(),
        "http://url2".to_string(),
        "http://url3".to_string(),
    ];
    rt.executor()
        .spawn(tx.send_all(stream::iter_ok(urls)).map(|_| ()).map_err(|_| ()));

    rt.shutdown_on_idle().wait()
        .map_err(|()| io::Error::new(io::ErrorKind::Other, "shutdown failure"))
}

#[derive(Debug)]
struct DownloadContents;
#[derive(Debug)]
struct DownloadError;

fn download(url: &str) -> Box<Future<Item = DownloadContents, Error = DownloadError> + Send> {
    // TODO: actually download here

    match url {
        // url2 always fails
        "http://url2" => {
            println!("FAILED downloading: {}", url);
            let future = Delay::new(Instant::now() + Duration::from_millis(1000))
                .map_err(|_| DownloadError)
                .and_then(|()| Err(DownloadError));
            Box::new(future)
        },
        // url3 always timeouts
        "http://url3" => {
            println!("TIMEOUT downloading: {}", url);
            let future = Delay::new(Instant::now() + Duration::from_millis(5000))
                .map_err(|_| DownloadError)
                .and_then(|()| Ok(DownloadContents));
            Box::new(future)
        },
        // everything else succeeds
        _ => {
            println!("SUCCESS downloading: {}", url);
            let future = Delay::new(Instant::now() + Duration::from_millis(50))
                .map_err(|_| DownloadError)
                .and_then(|()| Ok(DownloadContents));
            Box::new(future)
        },
    }
}