Function fastly::cache::simple::get_or_set_with

source ·
pub fn get_or_set_with<F>(
    key: impl Into<CacheKey>,
    make_entry: F
) -> Result<Option<Body>, CacheError>
where F: FnOnce() -> Result<CacheEntry, Error>,
Expand description

Get the entry associated with the given cache key if it exists, or insert and return an entry specified by running the given closure.

The closure is only run when no value is present for the key, and no other client is in the process of setting it. It takes no arguments, and returns either Ok with a CacheEntry describing the entry to set, or Err with an anyhow::Error. The error is not interpreted by the API, and is solely provided as a user convenience. You can return an error for any reason, and no value will be cached.

§Argument type conversion

See the From impls for Bytes to see which types can be used as a key.

§Example successful insertion

let value = get_or_set_with("my_key", || {
    Ok(CacheEntry {
        value: "hello!".into(),
        ttl: Duration::from_secs(60),
    })
})
.unwrap()
.expect("closure always returns `Ok`, so we have a value");
let cached_string = value.into_string();
println!("the cached string was: {cached_string}");

§Example unsuccessful insertion

let mut tried_to_set = false;
let result = get_or_set_with("my_key", || {
    tried_to_set = true;
    anyhow::bail!("I changed my mind!")
});
if tried_to_set {
    // if our closure was run, we can observe its error in the result
    assert!(matches!(result, Err(CacheError::GetOrSet(_))));
}