[][src]Function fastly::select

pub fn select<I>(
    pending_reqs: I
) -> (Result<Response, SendError>, Vec<PendingRequest>) where
    I: IntoIterator<Item = PendingRequest>, 

Given a collection of PendingRequests, block until the result of one of the requests is ready.

This function accepts any type which can become an iterator that yields requests; a common choice is Vec<PendingRequest>.

Returns a tuple (result, remaining), where:

  • result is the result of the request that became ready.

  • remaining is a vector containing all of the requests that did not become ready. The order of the requests in this vector is not guaranteed to match the order of the requests in the argument collection.

Examples

Selecting using the request URI

We can use the RequestExt::backend_request trait method to inspect the request that a response came from. In this case, we will use the request's URI to see which finished first.

use fastly::{select, Error, Request};

// Send two asynchronous requests, and store the pending requests in a vector.
let req1 = Request::get("http://www.origin.org/meow")
    .send_async("TheOrigin")?;
let req2 = Request::get("http://www.origin.org/woof")
    .send_async("TheOrigin")?;
let pending_reqs = vec![req1, req2];

// Wait for one of the requests to finish.
let (resp, _remaining) = select(pending_reqs);

// Return an error if the request was not successful.
let resp = resp?;

// Inspect the response metadata to see which backend this response came from.
match resp
    .get_backend_request()
    .unwrap()
    .get_url()
    .path()
{
    "meow" => println!("I love cats!"),
    "woof" => println!("I love dogs!"),
    _ => panic!("unexpected result"),
}

Selecting using the backend name

We can use the RequestExt::fastly_metadata trait method to identify which pending request in the given collection finished. Consider this example, where two requests are sent asynchronously to two different associated backends.

use fastly::{select, Error, Request};

// Send two asynchronous requests, and store the pending requests in a vector.
let req1 = Request::get("http://www.origin-1.org/")
    .send_async("origin1")?;
let req2 = Request::get("http://www.origin-2.org/")
    .send_async("origin2")?;
let pending_reqs = vec![req1, req2];

// Wait for one of the requests to finish.
let (resp, _remaining) = select(pending_reqs);

// Return an error if the request was not successful.
let resp = resp?;

// Inspect the response to see which backend this response came from.
match resp.get_backend_name().unwrap() {
    "origin1" => println!("origin 1 responded first!"),
    "origin2" => println!("origin 2 responded first!"),
    _ => panic!("unexpected result"),
}

Panics

Panics if the argument collection is empty, or contains more than fastly_shared::MAX_PENDING_REQS requests.