jaemk / cached

Rust cache structures and easy function memoization
MIT License
1.58k stars 96 forks source link

Cached key result async not working #82

Closed tqwewe closed 3 years ago

tqwewe commented 3 years ago

Is it possible to have an async function with the cached_key_result! macro?

I cannot get it to work... here's a basic example:

cached_key_result! {
    CACHE: SizedCache<String, String> = SizedCache::with_size(100);
    Key = { id.to_owned() };
    async fn foo(id: String) -> Result<String, &'static dyn std::error::Error> = {
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        Ok("Hey".to_string())
    }
}

It doesn't work with the async keyword there.. but when you remove the async keyword (and the use of tokio sleep), it works.

jaemk commented 3 years ago

hey @Acidic9 , async functions currently only work with the proc macro. The following should do the trick


use cached::proc_macro::cached;
use cached::SizedCache;

#[cached(
    type = "SizedCache<String, String>",
    create = "{ SizedCache::with_size(100) }",
    convert = r#"{ id.to_owned() }"#
)]
async fn foo(id: String) -> Result<String, &'static dyn std::error::Error> {
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    Ok("Hey".to_string())
}
tqwewe commented 3 years ago

Ah okay, but can I get access to the global cache variable with this? I need to manually invalidate keys.

tqwewe commented 3 years ago

I've just found that I can do name = "CACHE".. but now my issue is how can I make this public and other modules can import CACHE?

jaemk commented 3 years ago

I believe the cache visibility is set to the function's visibility: https://github.com/jaemk/cached/blob/12858a8a4af7f278e32ae90383d7483a54f829c6/cached_proc_macro/src/lib.rs#L289

Alternatively, you could have a pub fn invalidate_key(...) that does the cache mutation