google-apis-rs / google-cloud-rs

Asynchronous Rust bindings for Google Cloud Platform APIs.
176 stars 48 forks source link

Add timeout support to pub/sub #31

Closed dalloriam closed 3 years ago

dalloriam commented 3 years ago

Hi! This is just a small change to the pub/sub receive logic. As it is now, there's no way of politely stopping the subscription from pulling more messages, which is a bit of a pain when consuming from a stoppable thread.

I added a new Subscription::receive_timeout() method which accepts a timeout argument, and I extracted the common logic between the two receive methods.

Feel free to change the interface as you like :smile:

Cheers!

Hirevo commented 3 years ago

Hello ! I'm sorry for my long absence.
Regarding this issue, I'm not sure if google-cloud itself should implement timeouts.
I think that the following code should work just fine for adding a timeout when receiving messages:

use std::time::Duration;

// for tokio:
use tokio::time::timeout;
// for async-std:
use async_std::future::timeout;

let duration = Duration::from_secs(5);
while let Some(message) = timeout(duration, subscription.receive()).await? {
    // If the timeout was reached, that question mark would catch it ----^

    // So the message here has been received on time and can be processed ...
}

So, I am going to close the PR for now.
If you find that this solution does not work for your use-case, feel free to add a new comment and we can re-open the PR.