Tink.Cache (Tink v1.0.0)

Copy Markdown View Source

Cachex-backed response cache with per-resource TTLs, per-user isolation, opt-out support, and automatic invalidation on writes.

Configuration

config :tink,
  cache: [
    enabled:  true,
    max_size: 1_000
  ]

Disabling in tests

# config/test.exs
config :tink, cache: [enabled: false]

Per-call bypass

client_no_cache = %{client | cache: false}
{:ok, accounts} = Tink.Accounts.list(client_no_cache)

TTLs by resource type

TTL keyDurationUsed for
:categories24 hoursEnrichment categories
:providers2 hoursProvider lists and details
:statistics1 hourStatistics query results
:default5 minutesAccounts, investments, loans, etc
:balances1 minuteAccount balances
:credentials30 secondsCredential status

Cache key pattern

Keys follow "user_id:resource:identifier". Invalidate a whole user's entries with invalidate_user/1.

Summary

Functions

Delete a specific cache key.

Whether caching is enabled per application config.

Fetch a value from cache; call fallback on miss and populate cache.

Get a cached value directly. Returns {:ok, value} or {:error, :not_found}.

Build a global (non-user-scoped) cache key.

Invalidate all entries whose key starts with prefix.

Invalidate all cache entries for a user ID.

Build a scoped cache key: user_id:resource:extra.

Store a value manually.

Return raw Cachex stats for debugging.

Return the TTL in ms for a given TTL key.

Functions

delete(key)

@spec delete(String.t()) :: :ok

Delete a specific cache key.

enabled?()

@spec enabled?() :: boolean()

Whether caching is enabled per application config.

fetch(key, ttl_key \\ :default, cache_on \\ true, fallback)

@spec fetch(String.t(), atom(), boolean(), (-> {:ok, any()} | {:error, any()})) ::
  {:ok, any()} | {:error, any()}

Fetch a value from cache; call fallback on miss and populate cache.

Respects cache: false on the caller-supplied client_cache flag.

get(key)

@spec get(String.t()) :: {:ok, any()} | {:error, :not_found}

Get a cached value directly. Returns {:ok, value} or {:error, :not_found}.

global_key(resource, extra \\ nil)

@spec global_key(String.t(), String.t() | nil) :: String.t()

Build a global (non-user-scoped) cache key.

invalidate_prefix(prefix)

@spec invalidate_prefix(String.t()) :: :ok

Invalidate all entries whose key starts with prefix.

invalidate_user(user_id)

@spec invalidate_user(String.t()) :: :ok

Invalidate all cache entries for a user ID.

key(user_id, resource, extra \\ nil)

@spec key(String.t(), String.t(), String.t() | nil) :: String.t()

Build a scoped cache key: user_id:resource:extra.

put(key, value, opts \\ [])

@spec put(String.t(), any(), keyword()) :: :ok

Store a value manually.

stats()

@spec stats() :: {:ok, map()} | {:error, map()}

Return raw Cachex stats for debugging.

ttl(key)

@spec ttl(atom()) :: non_neg_integer()

Return the TTL in ms for a given TTL key.