Skip to main content

cached

Attribute Macro cached 

Source
#[cached]
Expand description

Attribute macro for caching async functions.

Transforms an async function to return a builder that can be configured with backend and policy before execution.

§Attributes

  • prefix = "..." - Custom prefix for the cache key (default: function name)

§Example

use hitbox_fn::cached;

#[cached]
async fn fetch_user(id: UserId, tenant: TenantId) -> Result<User, Error> {
    // expensive operation
}

// With custom prefix
#[cached(prefix = "user_data")]
async fn fetch_user(id: UserId) -> Result<User, Error> {
    // expensive operation
}

// Zero-argument function
#[cached(prefix = "app_config")]
async fn get_config() -> Result<Config, Error> {
    // expensive operation
}

// Usage with pre-configured cache
let cache = Cache::builder()
    .backend(backend)
    .policy(policy)
    .build();

let user = fetch_user(UserId(42), TenantId("acme".into()))
    .cache(&cache)
    .await?;

// Usage with context
let (user, ctx) = fetch_user(UserId(42), TenantId("acme".into()))
    .cache(&cache)
    .with_context()
    .await;
println!("Cache status: {:?}", ctx.status);

// Usage with inline configuration
let user = fetch_user(UserId(42), TenantId("acme".into()))
    .backend(backend)
    .policy(policy)
    .await?;